我有一个 AFHTTPClient 的子类,实现了 NSCoding 协议方法:
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (!self)
return nil;
self.isLoggedIn = [aDecoder decodeBoolForKey:@"isLoggedIn"];
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder {
[super encodeWithCoder:aCoder];
[aCoder encodeBool:self.isLoggedIn forKey:@"isLoggedIn"];
}
我还实现了为令牌设置默认标头的方法,并在那里存档了客户端:
- (void)setAuthorizationHeaderWithToken:(NSString *)token {
[self setDefaultHeader:@"Authorization" value:[NSString stringWithFormat:@"OAuth %@", token]];
[self setIsLoggedIn:YES];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:kGCClient];
[[NSUserDefaults standardUserDefaults] synchronize];
}
我- (id)initWithBaseURL:(NSURL *)url
在子类的实现中反序列化客户端:
- (id)initWithBaseURL:(NSURL *)url {
NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:kGCClient];
GCClient *client = [NSKeyedUnarchiver unarchiveObjectWithData:data];
if (client)
return self = client;
self = [super initWithBaseURL:url];
if (!self) {
return nil;
}
[self setIsLoggedIn:NO];
return self;
}
问题是,一旦我登录,下次我打开应用程序时,它会在AFHTTPClient
类- (id)initWithCoder:(NSCoder *)aDecoder
方法中崩溃客户端的反序列化,在第一次尝试解码对象时,在调试器中它说返回的值是不是 Objective-C 对象。
NSURL *baseURL = [aDecoder decodeObjectForKey:@"baseURL"];