Pages

Saturday, July 31, 2010

IPhone:Store and get back Image in NSUserDefault

In NSuserDefault, We can't Store Image As object. bcoz the size of image is much larger rather then any general object.
So Q. is, how to store image in NSUserDefault?

it Is So simple as Storing object, we have to just change the image to objectof NSData and store it.
same as following code:

Save image to NSUserDefault:
NSData *imageData;
// create NSData-object from image
imageData = UIImagePNGRepresentation([dic objectForKey:[NSString stringWithFormat:@"%d",i]]);
// save NSData-object to UserDefaults
[[NSUserDefaults standardUserDefaults] setObject:imageData forKey:[NSString stringWithFormat:@"%d",i]];

Load Image from NSUserDefault:
          NSData *imageData;
          // Load NSData-object from NSUserDefault
          imageData = [[NSUserDefaults standardUserDefaults] valueForKey:[NSString stringWithFormat:@"%d",i]];
          // get Image from NSData
   [image setObject:[UIImage imageWithData:imageData] forKey:[NSString stringWithFormat:@"%d",i]];
Note: image is Object of UIImage

2 comments:

  1. Hi I need help regarding the ([dic objectForKey:[NSString stringWithFormat:@"%d",i]]);

    my xcode is saying dic undeclared what do I do?

    ReplyDelete
  2. It is not clear to understand but i think, u r not creating the NSdictionay "dic" on particular view/.h file so define it and use.

    ReplyDelete