编辑:检查并重新检查了文件路径、归档和取消归档的代码,没有发现任何错误。App File System 在我不知道的启动之间是否存在问题?
我正在使用 NSCoder 在我的应用程序中存储图像。我创建了一个唯一的文件路径,将该文件路径存储到 Core Data,并使用文档中的相同文件路径归档图像。
在应用程序第一次启动时,一切都按预期工作 - 保存在 Core Data 中的文件路径用于取消归档存储在 Documents 中的图像。然而,在随后的启动中,unarchiver 返回 nil,我遇到了崩溃。
ImageForArchiving.m - 要使用 init 和 encode 方法保存的对象
+ (ImageForArchiving *)createImageWithImage:(NSData*)data andDate:(NSDate*)date {
ImageForArchiving *archiveImage = [[ImageForArchiving alloc] init];
[archiveImage setDate:date];
[archiveImage setImageData:data];
return archiveImage;
}
- (id) initWithCoder: (NSCoder *)coder
{
if (self = [super init])
{
[self setDate: [coder decodeObjectForKey:@"date"]];
[self setImageData: [coder decodeObjectForKey:@"image"]];
}
return self;
}
- (void) encodeWithCoder: (NSCoder *)coder
{
[coder encodeObject:self.date forKey:@"date"];
[coder encodeObject:self.imageData forKey:@"image"];
}
保存到存档、核心数据、创建文件路径和解档代码
- (void)saveItemsAtFilePath:(NSString*)filePath andImageToArchive:(ImageForArchiving*)imageRecord {
[NSKeyedArchiver archiveRootObject:imageRecord toFile:filePath];
}
- (void)loadItemsWithFilePath:(NSString*)filePath {
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
ImageForArchiving *image = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
NSLog(@"image %@", image.date);
} else {
NSLog(@"nothing saved");
}
}
-(void)saveToCoreDataWithFilePath:(NSString*)filePath{
AppDelegate *delegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = delegate.managedObjectContext;
NSManagedObject *photoAndDate = [NSEntityDescription insertNewObjectForEntityForName:@"Image" inManagedObjectContext:context];
[photoAndDate setValue:[NSDate date] forKey:@"date"];
[photoAndDate setValue:filePath forKey:@"image"];
NSError *error = nil;
if (![context save:&error]) {
NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
}
}
- (NSString *)createPathForDataFile
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
documentsPath = [documentsPath stringByExpandingTildeInPath];
NSError *error = nil;
if ([fileManager fileExistsAtPath: documentsPath] == NO)
{
[fileManager createDirectoryAtPath:documentsPath withIntermediateDirectories:YES attributes:nil error:&error];
}
NSString *stringForSaving = [[NSUUID UUID]UUIDString];
NSString *filePath = [documentsPath stringByAppendingPathComponent:stringForSaving];
return filePath;
}
循环通过 Core Data 数组加载数据源。未归档对象的添加是 w