简体   繁体   中英

iPhone:How can I store UIImage using NSUserDefaults?

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 and userInfo.categoryImage is UIImage variable.

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

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

如果您是我,我将UIImage保存到文件中(使用[myImage hash];生成文件名),然后使用NSUserDefault ;-)将文件名另存为NSString。

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

Store:

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

Restore:

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

Image Save on NSUserDefaults :

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

Image retrieve on NSUserDefaults:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM