プロフィール名と人々の画像を持つテーブルビューでアプリを試しています.テーブルビューは編集可能で、新しい名前と写真を追加し、既存のものを削除し、テーブルを再配置することが可能です..テーブルビューとその変更を保存する必要があります.コアデータの使用..ほぼ完了しましたが、コアデータ部分に問題があります.
テーブルセルのデータ永続性を提供するためにコアデータを実装しました.アプリを再起動するたびに、テーブルセルは最後に行われた変更を保持します..しかし、セル画像が読み込まれません..その画像を永続化するにはどうすればよいですか?
NSManagedObject *person1 = [NSEntityDescription
insertNewObjectForEntityForName:@"Person"
inManagedObjectContext:context];
NSManagedObject *person2 = [NSEntityDescription
insertNewObjectForEntityForName:@"Person"
inManagedObjectContext:context];
[person1 setValue:@"Bruce" forKey:@"personName"];
UIImage *image1 = [UIImage imageNamed:@"image1.jpg"];
NSData *imageData1 = UIImageJPEGRepresentation(image1, 0.9);
[person1 setValue:imageData1 forKey:@"personPicture"];
NSLog(@"Image1 data %@",imageData1);
[person2 setValue:@"Alfred" forKey:@"personName"];
UIImage *image2 = [UIImage imageNamed:@"image2.jpg"];
NSData *imageData2 = UIImageJPEGRepresentation(image2, 0.9);
[person2 setValue:imageData2 forKey:@"personPicture"];
NSError *error;
if (![context save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
その後、フェッチは次のように行われました
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"Person" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSError *error1 = nil;
self.persons = [[context executeFetchRequest:fetchRequest error:&error1] mutableCopy];
これdidFinishLaunchingWithOptions
は appDelegate で行われました。その後、データはcellForRowAtIndexPath
tableview クラス実装ファイルのメソッドで次のように使用されました。
Person *thisPerson = [persons objectAtIndex:indexPath.row];
cell.textLabel.text = thisPerson.personName;
UIImage *image = [UIImage imageWithData:[thisPerson valueForKey:@"personPicture"]];
if ( image == nil ) {
image = [UIImage imageNamed:@"QuestionMark.jpg"];
}
cell.imageView.image = image;
セルは適切にロードされています..そして、私が行ったすべての編集部分も保存および再ロードされています..アプリを初めてロードするときに画像が適切にロードされます..再起動すると、QuestionMark.jpg画像が表示されます..画像が nil であるため、NSLog を使用して最初の画像データを表示しようとしたところ、次のようになりました。
2012-09-07 17:05:59.395 Sample Project[1688:fb03] Image1 data <ffd8ffe0 00104a46
49460001 01000001 00010000 ffe10058 45786966 00004d4d 002a0000 00080002 01120003
00000001 00010000 87690004 00000001 00000026 00000000 0003a001 00030000 00010001
0000a002 00040000 00010000 00bea003 00040000 00010000 01090000 .........
...... .............. 7ff4d668 0356803f 357e307f c94ff14f fd858ffe
9af4ba00 f39a00cf a00d0a00 cfa00280 0a002803 ffd9>
ドットを追加した場所にはもっとたくさんありました..とにかく..これは、データが保存されていることを示しているようです..