iOS detachNewThreadSelector泄漏

时间:2011-02-23 18:54:55

标签: iphone objective-c multithreading uiscrollview nsautoreleasepool

我有一个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方法的代码中。如果您对此代码感到好奇,我将其包含在下面。

- (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];
   }
}

非常感谢任何想法。

2 个答案:

答案 0 :(得分:0)

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

UIKit Framework Reference Introduction

答案 1 :(得分:0)

使用以下

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

而不是

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

它消除了内存泄漏。