I save a custom object in NSUserDefults the object has more than one property ,
i initialize the value of the custom object in the AppDelegate ,
my problem is that when i try to retrieve the custom object property “userToken” in the viewcontroller didLoad method it works and the data is correct but when i retrieve it in another method in the view controller i get NULL note that the other property “uId” returns the correct value and i’m retrieving the objects in same way
what did i do wrong here ? help is really appreciated
here’s how i save and retrieve the object
+(void)SaveUser:(User *)user
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSData *userData = [NSKeyedArchiver archivedDataWithRootObject:user];
[userDefaults setObject:userData forKey:@"User"];
[userDefaults synchronize];
}
+(User*)retrieveUser
{
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
NSData *userData = [ud objectForKey:@"User"];
User *user = [NSKeyedUnarchiver unarchiveObjectWithData:userData];
return user;
}
and here’s the implementation of the User object
- (id)initWithCoder:(NSCoder *)decoder
{
self = [super init];
if (self)
{
//uId and userToken are of type NSString
self.uId = [decoder decodeObjectForKey:@"UID"];
self.userToken = [decoder decodeObjectForKey:@"DeviceToken"];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder
{
[encoder encodeObject:self.uId forKey:@"UID"];
[encoder encodeObject:self.userToken forKey:@"DeviceToken"];
}
Try this :
Also note that + mean as static function that didn’t have access to class properties make every thing in your saveuser or retrieveuser functions also decode without call another method out of class to decode it . that why maybe your + method get always null value when you use it out of loadview