2013-10-16 113 views
0

嘗試使用核心數據將圖像添加到數據庫。用戶使用視圖控制器輸入文本字段和圖像到數據庫。用戶使用UIImagePickerController選擇一個圖像。代碼是:使用核心數據將圖像添加到數據庫

- (void) add 
{ 
NSManagedObjectContext *context = [app managedObjectContext]; 

Exercises *exercises = [NSEntityDescription insertNewObjectForEntityForName:@"Exercises" inManagedObjectContext:context]; 

exercises.name = name.text; 
exercises.difficulty = difficulty.text; 
exercises.type = type.text; 
exercises.instructions = instructions.text; 
NSData* image1 = [NSData dataWithData:UIImagePNGRepresentation(imageView.image)]; 
[NSManagedObject setValue:image1 forKey:@"imageView"]; 

[self dismissViewControllerAnimated:YES completion:nil]; 

誤差是終止應用程序由於未捕獲的異常「NSUnknownKeyException」,原因:「[setValue方法:forUndefinedKey:]:此類不是密鑰值的關鍵ImageView的兼容編碼-」。關鍵是什麼?我甚至會以正確的方式去做這件事嗎?順便說一句,保存和檢索文本正常工作。我唯一的問題添加圖像。

回答

4

召喚:

[NSManagedObject setValue:image1 forKey:@"imageView"]; 

試圖調用setValue:forKey:在類NSManagedObject。該類不執行該方法,因此引發異常。

也許你想打電話給exercises,你剛剛創建的NSManagedObject的實例 - 它是否有一個名爲imageView的數據屬性?

在樣式和性能方面,訪問特定設置器的點符號是首選,因爲您已經用於所有其他屬性,但與其後面的PNG編碼相比,它不太可能成爲問題所以我不會擔心它。

+0

是的,這是解決辦法,但我有一對夫婦的錯誤。它的工作原理是這樣的:NSData * img = [NSData dataWithData:UIImagePNGRepresentation(imageView.image)]; [Exercises.self setValue:img forKey:@「image1」];謝謝。 – pjv

3

嘗試將文件保存在文檔目錄中,並在數據庫中添加圖像路徑。

您可以通過訪問圖片:

[[UIImageView alloc]initWithImage:[UIImage imageWithData: 
    [NSData dataWithContentsOfFile:@"PathStoredInDatabase"]]]; 
相關問題