iPhone:如何使用 NSUserDefaults 存储 UIImage?

iPhone:How can I store UIImage using NSUserDefaults?(iPhone:如何使用 NSUserDefaults 存储 UIImage?)

本文介绍了iPhone:如何使用 NSUserDefaults 存储 UIImage?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I cannot save image using nsuserdefaults and crash my app and I also used custom class UserInfo which used

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

-(id)initWithCoder:(NSCoder *)decoder 和 userInfo.categoryImage 是 UIImage 变量.

-(id)initWithCoder:(NSCoder *)decoder and userInfo.categoryImage is UIImage variable.

原因:'-[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 ???

So Please help me how can i store and retrieve uiimage using nsusedefaults???

推荐答案

UIImage 没有实现 NSCoding 协议,这就是你报错的原因.

UIImage does not implement NSCoding protocol, this is why you have the error.

商店:

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];

这篇关于iPhone:如何使用 NSUserDefaults 存储 UIImage?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:iPhone:如何使用 NSUserDefaults 存储 UIImage?

基础教程推荐