【问题标题】:iOS detachNewThreadSelector leakingiOS detachNewThreadSelector 泄漏
【发布时间】:2011-02-23 18:54:54
【问题描述】:

我有一个 UIScrollView,我要在其中加载一些图像。有时我会对图像应用效果,并且需要一些时间来进行预加载,所以我决定使用 detachNewThreadSelector 在不同的线程上执行此操作。为此,我正在使用 gitHub 上的 KTPhotoBrowser。

所以基本上,我有这样的功能。

- (void)setCurrentIndex:(NSNumber *)newIndex
{

   NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

   currentIndex_ = [newIndex integerValue];

   [self loadPhoto:currentIndex_];
   [self loadPhoto:currentIndex_ + 1];
   [self loadPhoto:currentIndex_ - 1];
   [self unloadPhoto:currentIndex_ + 2];
   [self unloadPhoto:currentIndex_ - 2];

  [self setTitleWithCurrentPhotoIndex];
  [self toggleNavButtons];
  [pool release];

}

我用

来称呼它
[NSThread detachNewThreadSelector:@selector(setCurrentIndex:) toTarget:self withObject:[NSNumber numberWithInt:5]];

当我运行它时,它似乎正在泄漏。我开始怀疑是否应该在 loadPhoto 方法中的代码周围放置 AutoRelease 池。如果您对此代码感到好奇,我已将其包含在下面。

- (void)loadPhoto:(NSInteger)index
{
   if (index < 0 || index >= photoCount_) {
      return;
   }

   id currentPhotoView = [photoViews_ objectAtIndex:index];
   if (NO == [currentPhotoView isKindOfClass:[KTPhotoView class]]) {
      // Load the photo view.
      CGRect frame = [self frameForPageAtIndex:index];
      KTPhotoView *photoView = [[KTPhotoView alloc] initWithFrame:frame];
      [photoView setScroller:self];
      [photoView setIndex:index];
      [photoView setBackgroundColor:[UIColor clearColor]];

      // Set the photo image.
      if (dataSource_) {
         if ([dataSource_ respondsToSelector:@selector(imageAtIndex:photoView:)] ==    NO) {
            UIImage *image = [dataSource_ imageAtIndex:index];
            [photoView setImage:image];
         } else {
        [dataSource_ imageAtIndex:index photoView:photoView];
         }
      }

      [scrollView_ addSubview:photoView];
      [photoViews_ replaceObjectAtIndex:index withObject:photoView];
      [photoView release];
   } else {
      // Turn off zooming.
      [currentPhotoView turnOffZoom];
   }
}

任何想法将不胜感激。

【问题讨论】:

  • 你能告诉我们你到底泄漏了什么类型的对象吗?
  • 我将很快通过仪器运行它,看看发生了什么。我会报告我的结果。

标签: iphone objective-c multithreading uiscrollview nsautoreleasepool


【解决方案1】:

您的代码似乎没问题,但您正在从另一个线程使用 UIKit。 UIKit 类只能在应用程序的主线程中使用。

UIKit Framework Reference Introduction

【讨论】:

  • 感谢您的回复。我将立即对此进行研究,看看我在哪里做得更好。
  • 这一限制在 iOS 4.0 中已经解除。
  • 不正确。从 iOS4 开始,UIKit 不是线程安全的,除了“在 UIKit 中绘制到图形上下文”。 developer.apple.com/library/ios/#releasenotes/General/…
【解决方案2】:

使用下面的

[self performSelectorInBackground:@selector(setCurrentIndex:) withObject:[NSNumber numberWithInt:5]];

而不是

[NSThread detachNewThreadSelector:@selector(setCurrentIndex:) toTarget:self withObject:[NSNumber numberWithInt:5]];

它消除了内存泄漏。

【讨论】:

    猜你喜欢
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-04
    • 2015-07-25
    • 2014-06-09
    • 2016-10-16
    相关资源
    最近更新 更多