我有一堂课,我想在整个应用程序中保持持久设置。这个类定义为:
@interface Archive : NSCoder <NSCoding> {
NSString *fromAddress;
NSString *toAddress;
... more ...
}
@property(nonatomic,retain) NSString *fromAddress;
@property(nonatomic,retain) NSString *toAddress;
+ (Archive *)sharedArchive;
-(void)encodeWithCoder:(NSCoder *)aCoder;
-(id)initWithCoder:(NSCoder *)aDecoder;
并实现为:
@synthesize fromAddress, toAddress;
+ (Archive *)sharedArchive
{
if (sharedArchive == nil) {
NSMutableData *data = [[NSMutableData alloc] initWithContentsOfFile:@"mydata"];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
sharedArchive = [unarchiver decodeObjectForKey:@"myapp"];
[unarchiver finishDecoding];
}
return sharedArchive;
}
+ (id)allocWithZone:(NSZone *)zone
{
sharedArchive = [super allocWithZone:NULL];
return sharedArchive;
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain
{
return self;
}
- (NSUInteger)retainCount
{
return NSUIntegerMax;
}
- (void)release
{
//do nothing
}
- (id)autorelease
{
return self;
}
-(void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:self.fromAddress forKey:@"fromAddress"];
[aCoder encodeObject:self.toAddress forKey:@"toAddress"];
}
-(id)initWithCoder:(NSCoder *)aDecoder {
self = [self initWithCoder:aDecoder];
fromAddress = [[aDecoder decodeObjectForKey:@"fromAddress"] retain];
toAddress = [[aDecoder decodeObjectForKey:@"toAddress"] retain];
return self;
}
应用程序委托 applicationWillTerminate 方法:
- (void)applicationWillTerminate:(UIApplication *)application {
/*
Called when the application is about to terminate.
See also applicationDidEnterBackground:.
*/
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:[Archive sharedArchive] forKey:@"myapp"];
[archiver finishEncoding];
[data writeToFile:@"myapp" atomically:YES];
}
我对存档/取消存档的概念很陌生。问题是我无法从数据文件中读回。我收到以下错误:
-[NSKeyedUnarchiver initForReadingWithData:]: 数据为 NULL
谁能解释我做错了什么?或者也许是保存/恢复持久数据的更好方法。我已经查看了 NSUserDefaults 类,但我认为这不适合我的情况……我不是要保存用户首选项。