1

我有一个 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];
   }
}

任何想法将不胜感激。

4

2 回答 2

0

您的代码看起来不错,但您正在使用另一个线程的 UIKit。UIKit 类只能在应用程序的主线程中使用。

UIKit 框架参考介绍

于 2011-02-23T21:52:30.503 回答
0

使用以下

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

代替

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

它消除了内存泄漏。

于 2012-11-02T10:08:56.057 回答