1

我有一個UIScrollView,我正在加載一些圖像。有時我應用效果的圖像,它需要一點做預加載,所以我決定在不同的線程上使用detachNewThreadSelector 。我正在使用gitHub上的KTPhotoBrowser。iOS detachNewThreadSelector泄漏

所以基本上,我有這樣的功能。

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

任何想法將不勝感激。

+0

你能告訴我們究竟是哪種物體泄漏嗎? – 2011-02-23 23:06:17

+0

我將很快通過儀器運行它,看看發生了什麼。我會回報我的結果。 – jabroni 2011-02-23 23:11:40

回答

0

您的代碼似乎沒問題,但您使用的是另一個線程的UIKit。 UIKit類只能在應用程序的主線程中使用。

UIKit Framework Reference Introduction

+0

感謝您的回覆。我會馬上研究,看看我做得更好。 – jabroni 2011-02-23 21:55:32

+0

這個限制已經在iOS 4.0中解除了。 – 2011-02-23 23:05:14

+1

不正確。從iOS4開始,除了「在UIKit中繪製圖形上下文」之外,UIKit不是線程安全的。 http://developer.apple.com/library/ios/#releasenotes/General/WhatsNewIniPhoneOS/Articles/iPhoneOS4.html#//apple_ref/doc/uid/TP40009559-SW29 – 2011-02-23 23:33:41

0

使用以下

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

,而不是

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

,它消除了內存泄漏。