使用NSThread解决iPhone上等待URL图片的问题

发布于 2024-09-01 03:18:15 字数 800 浏览 5 评论 0原文

因此,我在一种方法中有以下代码,我想将 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

鸩远一方 2024-09-08 03:18:15

您需要为线程创建一个自动释放池,否则您未显式释放的对象将不会被释放。请参阅 Apple 文档,其中本质上告诉您执行以下操作:

- (void)myThreadMainRoutine
{
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Top-level pool

  // Do thread work here.

  [pool release];  // Release the objects in the pool.
}

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:

- (void)myThreadMainRoutine
{
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Top-level pool

  // Do thread work here.

  [pool release];  // Release the objects in the pool.
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文