gpt4 book ai didi

ios - NSCoder 没有正确返回值

转载 作者:行者123 更新时间:2023-11-28 19:10:58 26 4
gpt4 key购买 nike

在下面的代码中,sharedInstance 方法中的属性从未正确设置,我不明白为什么。在我用存档器保存它之前,我似乎有正确的值。

  #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

如有任何帮助,我们将不胜感激。

最佳答案

这是因为你的全局变量 sharedinstance 在方法 - (id)initWithCoder:(NSCoder *)aDecoder 中总是 nil

关于ios - NSCoder 没有正确返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15553266/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com