【问题标题】:Using NSThread to solve waiting for image from URL on the iPhone使用 NSThread 解决 iPhone 上 URL 等待图片的问题
【发布时间】:2010-05-10 13:43:44
【问题描述】:

所以我在一个方法中有以下代码,我想将 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”中的代码解决这个问题?

谢谢

【问题讨论】:

    标签: iphone objective-c nsthread autorelease retain


    【解决方案1】:

    你需要为线程创建一个自动释放池,否则你没有明确释放的对象将不会被释放。请参阅Apple Docs,它基本上告诉您执行以下操作:

    - (void)myThreadMainRoutine
    {
      NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Top-level pool
    
      // Do thread work here.
    
      [pool release];  // Release the objects in the pool.
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-27
      • 2019-06-19
      • 1970-01-01
      • 2020-09-02
      • 1970-01-01
      • 2018-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多