다음 코드에서 sharedInstance 메서드에 속성이 올바르게 설정되지 않았으므로 이유를 파악할 수 없습니다. 내가 archiver와 함께 저장하기 전에 올바른 값을 가지고있는 것 같습니다.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
모든 도움을 주시면 감사하겠습니다. (NSCoder *) aDecoder 공유 인스턴스를 참조하지 않는 initWithCoder:
에서 항상 전무
당신은 그것에 대해 맞아,하지만 난 initWithCoder에서 디코더에서 나오는 값을 검사하고있어 실제로 때,이 얻을 : 포 [디코더 decodeObjectForKey : @ "USER_ID"] (ID) $ 1 = 용을 0x00000000을 –
키 = "user_id"가 없기 때문입니다. –
키가 있습니다. –