2011-10-01 75 views
6

NSUserDefaults的使用我无法保存图片和崩溃我的应用程序,我还使用自定义类的UserInfo其中使用iPhone:如何使用NSUserDefaults存储UIImage?

-(void)encodeWithCoder:(NSCoder *)encoder 
{ 
    NSData *imageData = UIImagePNGRepresentation(categoryImage); 
    [encoder encodeObject:categoryName forKey:@"name"]; 
    [encoder encodeObject:imageData forKey:@"image"]; 
} 

- (ID)的initWithCoder:(NSCoder *)解码器和userInfo.categoryImage是UIImage的变量。

原因: ' - [UIImage的encodeWithCoder:]:无法识别的选择发送到实例0x7676a70'

userInfo = [[UserInfo alloc] init]; 

userInfo.categoryName = categoryName.text; 
NSLog(@"Category Name:--->%@",userInfo.categoryName); 

userInfo.categoryImage = image; 

appDelegate.categoryData = [[NSMutableDictionary dictionaryWithObjectsAndKeys: 
           userInfo.categoryName, @"name",userInfo.categoryImage,@"image", nil] mutableCopy]; 


[appDelegate.categories addObject:appDelegate.categoryData]; 
NSLog(@"Category Data:--->%@",appDelegate.categories); 

[appDelegate.categories addObject:userInfo.categoryName]; 
[appDelegate.categories addObject:userInfo.categoryImage]; 

[self saveCustomObject:userInfo.categoryName]; 

[self saveCustomObject:userInfo.categoryImage]; 


-(void)saveCustomObject:(UserInfo *)obj 
{ 
    appDelegate.userDefaults = [NSUserDefaults standardUserDefaults]; 
    NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:obj]; 


    [appDelegate.userDefaults setObject:myEncodedObject forKey:@"myEncodedObjectKey"]; 
} 

所以请帮助我,我怎么可以存储和使用nsusedefaults检索的UIImage ???

+0

saveCustomObject几乎无法工作,因为它存储了同一个键的每个给定对象。 – Davyd

回答

21

UIImage的文件名保存为的NSString没有实现NSCoding协议,这就是为什么你有错误。

商店:

NSData* imageData = UIImagePNGRepresentation(image); 
NSData* myEncodedImageData = [NSKeyedArchiver archivedDataWithRootObject:imageData]; 
[appDelegate.userDefaults setObject:myEncodedImageData forKey:@"myEncodedImageDataKey"]; 
} 

还原:

NSData* myEncodedImageData = [appDelegate.userDefaults objectForKey:@"myEncodedImageDataKey"]; 
UIImage* image = [UIImage imageWithData:myEncodedImageData]; 
+0

如何在我的上述代码中使用商店请帮助 –

+0

使'UserInfo'类实现'NSCoding'协议并存档整个'userInfo'对象。阅读这篇文章的更多信息:http://stackoverflow.com/questions/3715038/how-to-store-a-nsuinteger-using-nscoding例如。 – Davyd

+0

我也使用NSCoding但也是应用程序崩溃 –

34

如果我是你,我会保存的UIImage到一个文件中(使用[MYIMAGE哈希]生成一个文件名),并使用NSUserDefault ;-)

+9

天啊,请接受这个答案。在NSUserDefaults上保存UIImage实在是一个愚蠢的想法。 – Mugunth

10

图像存储NSUserDefaults的上:

 [[NSUserDefaults standardUserDefaults] setObject:UIImagePNGRepresentation(image) forKey:@"image"]; 

图像检索NSUserDefaults的上:

NSData* imageData = [[NSUserDefaults standardUserDefaults] objectForKey:@"image"]; 
    UIImage* image = [UIImage imageWithData:imageData];