iPhone:How can I store UIImage using NSUserDefaults?(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?
- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
- android 4中的android RadioButton问题 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01
- 想使用ViewPager,无法识别android.support.*? 2022-01-01
- Android viewpager检测滑动超出范围 2022-01-01
- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01
- Android - 我如何找出用户有多少未读电子邮件? 2022-01-01
- 用 Swift 实现 UITextFieldDelegate 2022-01-01
- Android - 拆分 Drawable 2022-01-01