使用NSThread解决iPhone上等待URL图片的问题
因此,我在一种方法中有以下代码,我想将 UIImageView 图像设置为来自在线源的图像:
[NSThread detachNewThreadSelector:@selector(loadImage) toTarget:self withObject:nil];
然后在线程调用的方法中我有这样的:
- (void) loadImage
{
NSURL *url = [NSURL URLWithString:logoPath]; // logoPath is an NSString with path details
NSData *data = [NSData dataWithContentsOfURL:url];
logoImage.image = [UIImage imageWithData:data];
}
这很好用,但是我在调试器控制台中收到许多警告沿着以下思路:
2010-05-10 14:30:14.052 项目标题[2930:633f] *** _NSAutoreleaseNoPool():NSHTTPURLResponse 类的对象 0x169d30 自动释放但没有池 - 刚刚漏水
每次我调用新线程时,这种情况都会发生很多次,最终,在没有模式的情况下,在调用其中一些线程后,我得到了经典的“EXC_BAD_ACCESS”运行时错误。
我知道发生这种情况是因为我没有保留该对象,但是如何使用上面显示的“loadImage”中的代码解决这个问题?
谢谢
So I have the following code in a method which I want to set a UIImageView image to that of one from an online source:
[NSThread detachNewThreadSelector:@selector(loadImage) toTarget:self withObject:nil];
Then in the method called by the thread I have this:
- (void) loadImage
{
NSURL *url = [NSURL URLWithString:logoPath]; // logoPath is an NSString with path details
NSData *data = [NSData dataWithContentsOfURL:url];
logoImage.image = [UIImage imageWithData:data];
}
This works great however I get many warnings within the Debugger Console along the lines of:
2010-05-10 14:30:14.052
ProjectTitle[2930:633f] ***
_NSAutoreleaseNoPool(): Object 0x169d30 of class NSHTTPURLResponse
autoreleased with no pool in place -
just leaking
This occurs many times each time I call the new thread and then eventually, under no pattern, after calling a few of these threads I get the classic 'EXC_BAD_ACCESS' run-time error.
I understand that this is happening because I'm not retaining the object but how can I solve this with the code in 'loadImage' shown above?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要为线程创建一个自动释放池,否则您未显式释放的对象将不会被释放。请参阅 Apple 文档,其中本质上告诉您执行以下操作:
You need to create an autorelease pool for the thread otherwise objects which you do not explicitly release will not get released. See the Apple Docs, which essentially tell you to do the following: