我正在阅读初学iOS 5示例并尝试根据我的使用进行调整。我有一个DataManager单例对象,其属性为:
@property (nonatomic, strong) NSArray *frequencyArray;
@property (nonatomic, strong) NSMutableArray *networkArray;
当我使用ARC时,我的单身人员看起来像:
- (id)init {
if (self = [super init]) {
_networkArray = [[NSMutableArray alloc] init];
}
return self;
}
+ (id)sharedInstance {
if (sharedDmgr == nil) {
sharedDmgr = [[super allocWithZone:NULL] init];
}
return sharedDmgr;
}
+ (id)allocWithZone:(NSZone *)zone {
return [self sharedInstance];
}
- (id)copyWithZone:(NSZone *)zone {
return self;
}
我按照示例代码将此类符合NSCoding和NSCopying。我在这个类中创建了两个方法来归档自己,并取消归档自己。那些是:
- (NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingFormat:ARCHIVE_FILE_NAME];
}
- (void)archiveAppData {
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:self forKey:ARCHIVE_DATA];
// [archiver encodeObject:_frequencyArray forKey:DMGR_FREQUENCY_ARRAY];
// [archiver encodeObject:_networkArray forKey:DMGR_NETWORK_ARRAY];
[archiver finishEncoding];
// BOOL success = [data writeToFile:[self dataFilePath] atomically:YES];
NSError *error;
BOOL success = [data writeToFile:[self dataFilePath] options:NSDataWritingAtomic error:&error];
if (!success) {
NSLog(@"Could not write file %@", [error description]);
}
}
- (void)unarchiveAppData {
NSData *data = [[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath]];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
sharedDmgr = [unarchiver decodeObjectForKey:ARCHIVE_DATA];
// self.frequencyArray = [unarchiver decodeObjectForKey:DMGR_FREQUENCY_ARRAY];
// self.networkArray = [unarchiver decodeObjectForKey:DMGR_NETWORK_ARRAY];
[unarchiver finishDecoding];
}
我收到错误:
我用谷歌搜索,看到它指的是修改捆绑。但我不知道我在做什么,因为我以为我用我的[self dataFilePath]代码写了文档directoroy。无法写入文件错误Domain = NSCocoaErrorDomain Code = 513“The 操作无法完成。 (可可错误513.)“操作 无法完成。不允许操作“}
当我的应用程序重新激活时,我调用archiveAppData方法。当我的第一个viewController加载时,我调用unarchiveAppData。正如您从注释掉的代码中看到的那样,我试图仅对这两个数组进行编码,然后解码那些而不是DataManager对象本身,但这似乎也不起作用。对我做错了什么的想法?感谢。