I am trying to save a list of users (with UIImage property) to NSUserdefault whenever the user clicks on a certain tab in my app.
In my ‘user’ object, I implemented the encoding as shown below:
- (void)encodeWithCoder:(NSCoder *)encoder
{
NSURL *url = [NSURL URLWithString:self.avatar_url];
NSData *data = [NSData dataWithContentsOfURL:url];
self.avatar = [[[UIImage alloc] initWithData:data] autorelease];
[encoder encodeObject:UIImagePNGRepresentation(self.avatar) forKey:@"avatar"];
}
However, I realize that by doing this, my app hangs after clicking on the tab that triggers the saving to NSUserdefault. I attribute the slow performance to the conversion (and encoding) of a UIImage from a URL.
Is there a way to speed up this process of encoding and saving an image to NSUserdefault (that does not cause the app to lag).
The reason it is slow is because you are blocking the main thread until the image downloads. Whenever performing operations that rely on network activity you should move that to a background thread. And as @Richard J. Rosss III pointed out you can save the data directly, there is little reason to convert to an image then back to data unless you absolutely need a png and the original format was not png.
Concurrency Programming Guide