[英]How to save and display an image using core data
我試圖將使用應用程序拍攝的圖像保存到核心數據,然后將其顯示在UITableView中。 我寫了一些我認為應該有用的代碼,但事實並非如此。 先感謝您!
以下是保存圖像的代碼:
- (void)saveImage {
// NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(self.thumbImage)];
//
// [managedObjectContext setValue:imageData forKey:@"imageData"];
//
// NSLog(@"Saved to CoreData");
NSManagedObjectContext *context = [self managedObjectContext];
TimeTravelFeed *timeTravelFeed = [NSEntityDescription insertNewObjectForEntityForName:@"TimeTravelFeed" inManagedObjectContext:context];
NSData *imageData = UIImageJPEGRepresentation(thumbImage, 0.8f);
[timeTravelFeed setValue:imageData forKey:@"imageData"];
}
我正在展示它:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"Cell";
PhotoCell *cell = (PhotoCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
cell = [[PhotoCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
// Configure the cell...
TimeTravelFeed *feed = [timeTravelFeeds objectAtIndex:indexPath.row];
NSData *data = feed.imageData;
self.feedImage = [UIImage imageWithData:data];
cell.thumbImage = self.feedImage;
return cell;
}
您的代碼存在許多問題。
首先,正如已經指出的那樣,你沒有調用[context save:nil]
。
其次,您的單元格似乎沒有圖像視圖,只有圖像。 這不是很透明。 據推測,單元格負責將feedImage
屬性分配給某個圖像視圖。 最好給PhotoCell
一個圖像視圖屬性並填充它
cell.imageView.image = imageRetrieved;
第三,在單元格中,首先將轉換后的圖像分配給某個類變量( self.feedImage
)。 這不合邏輯,完全沒必要。 而是使用具有局部范圍的變量或直接將圖像分配給圖像視圖。
最后,你不應該在Core Data中存儲大的blob(照片)。 建議您僅存儲小圖像,例如縮略圖。 對於較大的文件,您應該將路徑存儲在Core Data實體中,將圖像文件存儲在documents目錄中。 這也可以通過在模型編輯器中選中此屬性的“允許外部存儲”來自動完成。
附加建議:在NSManagedObject
子類中進行轉換,這樣您就不必關心控制器的這種技術性。
看起來您沒有成功保存圖像。 嘗試將此添加到saveImage
if (![context save:&error]) {
NSLog(@"Some error", [error localizedDescription]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.