EDIT:ファイルパス、アーカイブおよびアーカイブ解除用のコードをチェックおよび再チェックしましたが、バグは見つかりませんでした。私が認識していない起動間のアプリ ファイル システムに関する問題はありますか?
NSCoder を使用してアプリに画像を保存しています。一意のファイル パスを作成し、そのファイル パスを Core Data に保存し、ドキュメント内の同じファイル パスを使用して画像をアーカイブします。
アプリを最初に起動すると、すべてが期待どおりに機能します。コア データに保存されたファイル パスを使用して、ドキュメントに保存されている画像が解凍されます。ただし、その後の起動では、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"];
}
アーカイブへの保存、Core Data、ファイル パスの作成、およびコードのアーカイブ解除
- (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;
}
コア データ配列をループしてデータ ソースをロードします。未公開物件の追加はw