iPhone:如何使用NSUserDefaults存储UIImage?

时间:2011-10-01 12:18:49

标签: iphone ios cocoa-touch uikit

我无法使用nsuserdefaults保存图像并崩溃我的应用程序而且我还使用了自定义类UserInfo

-(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

3 个答案:

答案 0 :(得分:34)

如果我是你,我会将UIImage保存到文件中(使用[myImage hash];生成文件名),并使用NSUserDefault将文件名保存为NSString; - )

答案 1 :(得分:23)

UIImage没有实现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];

答案 2 :(得分:9)

NSUserDefaults上的图像保存:

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

NSUserDefaults上的图像检索:

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