iPhone:如何使用NSUserDefaults存储UIImage? [英] iPhone:How can I store UIImage using NSUserDefaults?
问题描述
我无法使用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 *)解码器和 userInfo .categoryImage是UIImage变量。
-(id)initWithCoder:(NSCoder *)decoder and userInfo.categoryImage is UIImage variable.
reason:' - [UIImage encodeWithCoder:]:unrecognized selector sent to instance 0x7676a70' / p>
reason: '-[UIImage encodeWithCoder:]: unrecognized selector sent to instance 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!