我在NSUserDefults中保存一个自定义对象,该对象有多个属性, 我初始化AppDelegate中自定义对象的值, 我的问题是,当我尝试在viewcontroller didLoad方法中检索自定义对象属性“userToken”时,它工作,数据是正确的,但当我在视图控制器中的另一个方法中检索它时,我得到NULL注意另一个属性“uId “返回正确的值,我以相同的方式检索对象
我在这里做错了什么?非常感谢帮助
这是我如何保存和检索对象
+(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;
}
这里是User对象的实现
- (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"];
}
答案 0 :(得分:1)
试试这个: 另请注意,+ mean作为无法访问类属性的静态函数会使saveuser或retrieveuser函数中的所有内容都解码,而无需调用其他方法来解码它。这就是为什么你的+方法在loadview中使用它时总是会得到null值
+(void)SaveUser:(User *)user
{
NSUserDefaults *UserDefaults = [NSUserDefaults standardUserDefaults];
[UserDefaults setObject:[NSKeyedArchiver archivedDataWithRootObject:user] forKey:@"User"];
[UserDefaults synchronize];
}
+(User*)retrieveUser
{
NSUserDefaults *UserDefaults = [NSUserDefaults standardUserDefaults];
NSData *userData = [UserDefaults objectForKey:@"User"];
User *user = [NSKeyedUnarchiver unarchiveObjectWithData:userData];
return user;
}