Following this link: How do I archive two objects using NSKeyedArchiever? I am able to archieve an array and a singleton object. I can archieve and correctly unarchieve it at didFinishLaunchingWithOptions.
However, my singleton object does not persist past the app delegate. In the next view controller, the singleton variables goes back to its default value even though in didFinishLaunchingWithOptions, I did a NSLog and verified. Here is an example,
In application didFinishLaunchingWithOptions
:
Singleton *singleton = [Singleton sharedSingleton];
NSData *data = [NSData dataWithContentsOfFile:path];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
singleton = [unarchiver decodeObjectForKey:@"singleton"];
[unarchiver finishDecoding];
NSLog(@"singleton sorting after decode: %@", [singleton sort]);
// ouput: alphabet
Then, I alloc/init a viewController and set it as root view controller for my navigation controller:
navController = [[UINavigationController alloc] initWithRootViewController:viewController];
In viewController -> viewWillAppear,
I call a sorting function: [self sort...];
And in the sorting function, I call the singleton class:
Singleton *singleton = [Singleton sharedSingleton];
But now, NSLog(@"singleton sort: %@", [singleton sort]);
// output: amount NOT alphabet
I can post my Singleton code but I know it works. In fact, in my settings view controller, if I change the [singleton sort] variable, it will persist through all view controllers.
This is confusing me as to why my singleton object does not persist from app delegate to my view controllers. Any tips/hints are appreciated.
Thanks!!!
EDIT: Singleton class implementation
In Singleton.m:
static Singleton *shared = NULL;
+ (id)sharedSingleton
{
@synchronized(self)
{
if ( !shared || shared == NULL )
{
// allocate the shared instance, because it hasn't been done yet
NSLog(@"Allocating Singleton...");
shared = [[Singleton alloc] init];
}
return shared;
}
}
- (id)init
{
if ( self = [super init] )
{
sort = [[NSString alloc] initWithString:@"amount"];
showTutorial = YES;
}
return self;
}
-(id)initWithCoder:(NSCoder *)aDecoder
{
[super init];
[self setSort:[aDecoder decodeObjectForKey:@"sort"]];
[self setShowTutorial:[aDecoder decodeBoolForKey:@"showTutorial"]];
return self;
}
-(void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:sort forKey:@"sort"];
[aCoder encodeBool:showTutorial forKey:@"showTutorial"];
}
initWithCoder:
method? – Deepak Danduprolu