Reputation: 393
I use ASIHTTPRequest library to download picture, I store my picture in a NSMutableDictionnary (key=url, value =UIImage), which permit to me to download one time the picture I need for each of my views. This part works well.
Now I want to store my NSMutableDictionnary named "imagesDownloaded" in iPhone memory to download one time each images for all my application, I do it thanks to this code
UIImage *img = [[UIImage alloc] initWithData:[request responseData]];
[imagesDownloaded setValue:img forKey:request.url.description];
userDatas = [NSUserDefaults standardUserDefaults];
[userDatas setValue:imagesDownloaded forKey:@"Pictures"];
[userDatas synchronize];
But it doesn't work, when I do:
NSLog(@"%@", [userDatas objectForKey:@"Pictures"]);
The value is always "null".
What's wrong?
Thanks
Upvotes: 0
Views: 625
Reputation: 5120
As the others said, you cannot save an image directly into NSUserDefaults
.
Although you can save it as an encoded string or something else that can be saved in NSUserDefaults
, but since the data of an image is much bigger than normal NSUserDefaults
data, it's bad for performance if you save images into it.
The best way to do so is save your image as a file into iOS's file system, and then you just save the path of the image into NSUserDefaults
.
Upvotes: 1
Reputation: 10083
The object you are storing to the user defaults (and all of it's children) has to be a plist type of object, or in other words, NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary.
I recently did something similar to this, which involves code like this to store the item:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:appSettings];
[prefs setObject:myEncodedObject forKey:@"appSettings"];
[prefs synchronize];
My appSettings class required that I create the encodeWithCoder and initWithCoder methods, but once I did that, I was able to put the class into the user defaults.
Upvotes: 0
Reputation: 48398
You cannot store an image directly into NSUserDefaults
. From the documentation:
The
NSUserDefaults
class provides convenience methods for accessing common types such as floats, doubles, integers, Booleans, and URLs. A default object must be a property list, that is, an instance of (or for collections a combination of instances of):NSData
,NSString
,NSNumber
,NSDate
,NSArray
, orNSDictionary
. If you want to store any other type of object, you should typically archive it to create an instance ofNSData
.
Since you already have the data for the image ([request responseData]
), try storing that into the defaults. You can also try putting the NSData
objects directly into your array rather than the UIImage
objects, and then store that.
To learn more about using user defaults, check out Apple's User Defaults Programming Topics
Upvotes: 0