在多线程中释放对象

时间:2011-10-12 11:20:14

标签: objective-c ios multithreading memory-leaks nsthread

假设我创建了一个新线程并将一个对象传递给它。怎么发布呢?

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    float x=    scrollView.contentOffset.x/(self.view.frame.size.width/2 + 40 );
    int pg=round(x);
    pg=abs(x);
    currentPage=pg;
    if(pg!=currentIndex && pg+1 < pageCounter)
    {
        currentIndex=   pg; 
        NSNumber *num=[NSNumber numberWithInt:pg+1];
        [NSThread detachNewThreadSelector:@selector(getImageForPage:) toTarget:self withObject:num];
    }
}

//这是一个后台工作

-(void)getImageForPage:(NSNumber*)page{
    NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];
    int pg=[page intValue];
    UIButton *btn = (UIButton*)[scrl viewWithTag:pg];
    UIImageView *imgV = (UIImageView *)[btn viewWithTag:1111];      
    if(imgV.image==nil)
    {
        NSLog(@"currnt visible page %d ",currentPage);
        if(!isWorking)
        {
        UIImage *im=    [self imageFromPDFforPage:pg+1];        
            imgV.image = im;
        }
        else
            [self performSelector:@selector(getImageForPage:) withObject:[NSNumber numberWithInt:pg+1] afterDelay:3];
    }
    [pool drain];
}

我应该叫[游泳池排水];或[pool release];

- (UIImage *)imageFromPDFforPage:(int)page {
    isWorking=YES;
    CGPDFPageRef pageRef = CGPDFDocumentGetPage(pdf, page);
    CGRect pageRect = CGPDFPageGetBoxRect(pageRef, kCGPDFCropBox);  
    NSLog(@"page %d, w=  %f h= %f",page, pageRect.size.width,pageRect.size.height);
    UIGraphicsBeginImageContext(pageRect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context, CGRectGetMinX(pageRect),CGRectGetMaxY(pageRect));
    CGContextScaleCTM(context, 1, -1);  
    CGContextTranslateCTM(context, -(pageRect.origin.x), -(pageRect.origin.y));     
    CGAffineTransform transform = aspectFit(CGPDFPageGetBoxRect(pageRef, kCGPDFCropBox),
                                            CGContextGetClipBoundingBox(context));
    CGContextConcatCTM(context, transform);
    CGContextDrawPDFPage(context, pageRef);     
    UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    isWorking=NO;
    return finalImage;          
} 

我的理解是这个函数也在后台线程中调用。这里pdf是类变量。 我做错了吗?

2 个答案:

答案 0 :(得分:0)

(1)在非垃圾收集环境中,[pool drain][pool release]的行为相同。

(2)您在单独线程中传递的对象是自动释放的对象,因此您无需在scrollViewDidScroll:(UIScrollView *)scrollView中释放它。

顺便说一句,如果您的目标是支持GCD的iOS版本,那么您希望使用该技术而不是线程。

答案 1 :(得分:0)