1

I have one basic question here. I know we can use NSUserDefaults to store data that last forever in the device. But is there any other method/variable that we can use to store data for just one session i.e. the data will complete gone when the user close/shutdown the app and reopen it.

I am hoping that I could recall that data (e.g. an int) back in during the same session across different classes (view controllers)

Many thanks!!

4

2 回答 2

2

一个常见的做法是在您的应用程序委托中创建一个 ivar,以及设置和获取它的两种方法。

于 2013-11-03T12:50:06.777 回答
0

显然,您要寻找的不是持久性,而是跨多个类的数据可用性。执行此操作的常见模式是Singleton 模式。下面是一个示例实现。

@interface MySingleton : NSObject {
   NSString *someProperty;
}

@property (nonatomic, retain) NSString *someProperty;

+ (id)sharedManager;

@end


@implementation MyManager

@synthesize someProperty;

#pragma mark Singleton Methods

+ (id)sharedManager {
   static MyManager *sharedMyManager = nil;
   static dispatch_once_t onceToken;
   dispatch_once(&onceToken, ^{
      sharedMyManager = [[self alloc] init];
   });
   return sharedMyManager;
}

- (id)init {
   if (self = [super init]) {
     someProperty = [[NSString alloc] initWithString:@"Default Property Value"];
   }
   return self;
}

- (void)dealloc {
  // Should never be called, but just here for clarity really.
}
于 2013-11-03T13:00:58.573 回答