嗨,我正在为我的应用程序使用 iCloud 支持并UIDocument
用于存储。我能够将数据保存到 iCloud 并第一次获取相同的数据。但是当我在设备上删除并重新安装该应用程序时,似乎EXC BAD ACCESS
在尝试使用NSKeyUnarchiver
.
代码。
BuyerDocument.m // UIDocument Subclass
// Accessor for BuyerData
- (BuyerData *)data {
if (_data == nil) {
if (self.fileWrapper != nil) {
self.data = [self decodeObjectFromWrapperWithPreferredFilename:BUYER_FILENAME]; // BUYER_FILENAME = @"buyer.data"
} else {
self.data = [[BuyerData alloc] init];
}
}
return _data;
}
- (id)decodeObjectFromWrapperWithPreferredFilename:(NSString *)preferredFilename {
NSFileWrapper * fileWrapper = [self.fileWrapper.fileWrappers objectForKey:preferredFilename];
if (!fileWrapper) {
NSLog(@"Unexpected error: Couldn't find %@ in file wrapper!", preferredFilename);
return nil;
}
if([fileWrapper isRegularFile]){
NSLog(@"is regular wrapper");
}
NSData * data = [fileWrapper regularFileContents];
NSLog(@"data %@",data); // This logs successfully
// NSLog(@"data bytes %@",[data bytes]) // This also causes app to crash.
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data]; // App will crash here
return [unarchiver decodeObjectForKey:@"data"];
}
在此处加载买方文档。
- (void)loadDocAtURL:(NSURL *)fileURL {
// Open doc so we can read metadata
BuyerDocument * doc = [[BuyerDocument alloc] initWithFileURL:fileURL];
[doc openWithCompletionHandler:^(BOOL success) {
.......
BuyerData * data = doc.data;
....
[doc closeWithCompletionHandler:^(BOOL success) {
.....
}];
}
BuyerData.m
#define kVersionKey @"Version"
#define kNameKey @"Name"
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeInt:1 forKey:kVersionKey];
[encoder encodeObject:self.name forKey:kNameKey];
}
- (id)initWithCoder:(NSCoder *)decoder {
[decoder decodeIntForKey:kVersionKey];
NSString *nameData = [decoder decodeObjectForKey:kNameKey];
// NSLog(@">>>>>>>>>>>>>>>>>>> %@",name); // This logs for first 2-3 files and then crash occurs
return [self initWithName:nameData];
}
正如我所说,当我第一次添加数据时一切都运行良好,只是在删除并重新安装之后才开始发生崩溃。在此崩溃发生之前,还会获取前 3-4 个名称并将其显示在 tableview 中。试过这个但没有帮助我对UIDocument
and还很陌生NSCoding
。所以不能多说他们。但我猜一些问题可能与在NSData
那里迷路或损坏有关。我在这里错过了一些基本和重要的东西吗?我究竟做错了什么?