简体   繁体   English

尝试编码UIImage并存储到NSUserdefault时App会变慢

[英]App becomes slow when trying to encode UIImage and storing to NSUserdefault

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. 每当用户点击我的应用程序中的某个选项卡时,我都会尝试将用户列表(使用UIImage属性)保存到NSUserdefault。

In my 'user' object, I implemented the encoding as shown below: 在我的'user'对象中,我实现了编码,如下所示:

- (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. 但是,我意识到通过执行此操作,我的应用程序在单击触发保存到NSUserdefault的选项卡后挂起。 I attribute the slow performance to the conversion (and encoding) of a UIImage from a URL. 我将缓慢的性能归因于来自URL的UIImage的转换(和编码)。

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). 有没有办法加快编码和保存图像到NSUserdefault的过程(这不会导致应用程序滞后)。

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. 正如@Richard J. Rosss III指出你可以直接保存数据,除非你绝对需要一个png并且原始格式不是png,否则几乎没有理由转换为图像然后再转换回数据。

Concurrency Programming Guide 并发编程指南

If the URL is remote (rather than a local file:/// URL) then the performance issue is probably that of downloading it - look into using NSURLRequest and related classes to download the avatar asynchronously (in the background) and then store it to NSUserDefaults afterwards. 如果URL是远程的(而不是本地file:/// URL),则性能问题可能是下载它 - 请查看使用NSURLRequest和相关类异步下载头像(在后台),然后将其存储到之后NSUserDefaults

Also note that writing an image to NSUserDefaults is not the intended use case - you'd be better off writing it to a file in your documents directory: 另请注意,将图像写入NSUserDefaults并不是预期的用例 - 最好将其写入文档目录中的文件:

NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"avatar"];
[data writeToFile:path atomically:YES];

And to fetch: 并获取:

NSData *data = [NSData dataWithContentsOfFile:path];
UIImage *image = [UIImage imageWithData:data];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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