在下面的代碼中,屬性從未在sharedInstance方法中正確設置,我找不到原因。看起來我有正確的價值,但在我將它與存檔器一起保存之前。NSCoder沒有正確返回值
#import "User.h"
static User *sharedInstance = nil;
#define NAME @"name"
#define USER_ID @"id"
#define ACCOUNT_ID @"account_id"
#define USER_NAME @"username"
#define ADMIN @"admin"
#define CURRENT_USER @"current_user"
@implementation KSUser
+ (id)sharedInstance
{
@synchronized(self) {
if (sharedInstance == nil) {
NSData *userData = [[NSUserDefaults standardUserDefaults] objectForKey:CURRENT_USER];
if (userData) {
sharedInstance = [NSKeyedUnarchiver unarchiveObjectWithData:userData];
}
else {
sharedInstance = [[super alloc] init];
}
}
}
return sharedInstance;
}
- (void)populateFromJSON:(NSDictionary *)json
{
sharedInstance.name = json[NAME];
sharedInstance.accountId = json[ACCOUNT_ID];
sharedInstance.userId = json[USER_ID];
sharedInstance.userName = json[USER_NAME];
sharedInstance.admin = [json[ADMIN] boolValue];
sharedInstance.loggedIn = YES;
NSLog(@"values are: name: %@, %@, %@, %@", sharedInstance.name, sharedInstance.accountId, sharedInstance.userId, sharedInstance.userName);
}
- (void)logout
{
sharedInstance.name = nil;
sharedInstance.accountId = nil;
sharedInstance.userId = nil;
sharedInstance.userName = nil;
sharedInstance.admin = NO;
sharedInstance.loggedIn = NO;
[self saveState];
}
- (void)saveState
{
NSLog(@"values are: name: %@, %@, %@, %@", sharedInstance.name, sharedInstance.accountId, sharedInstance.userId, sharedInstance.userName);
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:sharedInstance];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:CURRENT_USER];
}
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:sharedInstance.userId forKey:USER_ID];
[aCoder encodeObject:sharedInstance.accountId forKey:ACCOUNT_ID];
[aCoder encodeObject:sharedInstance.name forKey:NAME];
[aCoder encodeObject:sharedInstance.userName forKey:USER_NAME];
[aCoder encodeBool:sharedInstance.admin forKey:ADMIN];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super init]) {
sharedInstance.userId = [aDecoder decodeObjectForKey:USER_ID];
sharedInstance.accountId = [aDecoder decodeObjectForKey:ACCOUNT_ID];
sharedInstance.name = [aDecoder decodeObjectForKey:NAME];
sharedInstance.userName = [aDecoder decodeObjectForKey:USER_NAME];
sharedInstance.admin = [aDecoder decodeBoolForKey:ADMIN];
}
return self;
}
@end
任何幫助將不勝感激。
你是對的,但實際上,當我檢查出來的的initWithCoder解碼器的值,我得到這個: PO [解碼器decodeObjectForKey:@「user_ID的」] (ID)1 $ = 00000000 –
2013-03-21 17:12:09
這是因爲你沒有這樣的key @「user_id」。 – 2013-03-21 17:16:15
鑰匙存在。 – 2013-03-21 17:19:48