2010-11-14 21 views
2

我正在用這個類加載圖像。當需要調用dealloc時,如何阻止它們加載,我需要幫助。這個類正在擴展UIImageView。還有任何其他建議設計類是讚賞,我想例如分發加載的字節。停止從一個新線程加載的照片

@implementation RCPhoto 

- (id)initWithFrame:(CGRect)frame delegate:(id)d { 
    if ((self = [super initWithFrame:frame])) { 
     // Initialization code 
     delegate = d; 
     self.contentMode = UIViewContentModeScaleAspectFit; 
    } 
    return self; 
} 

- (void)dealloc { 
    [super dealloc]; 

} 

#pragma mark Load photo 
- (void)loadImage:(NSString *)path { 
    // Create a new thread for loading the image 
    [NSThread detachNewThreadSelector:@selector(load:) 
          toTarget:self 
          withObject:path]; 
} 

- (void)load:(NSString *)path { 

    // You must create a autorelease pool for all secondary threads. 
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 

    //NSLog(@"RCPhoto loadImage into a new thread: %@", path); 
    NSURL *url = [NSURL URLWithString: path]; 
    NSData *data = [NSData dataWithContentsOfURL: url]; 
    UIImage *image = [[UIImage alloc] initWithData: data]; 

    [self performSelectorOnMainThread: @selector(performCompleteEvent:) 
          withObject: image 
         waitUntilDone: NO]; 

    [pool release]; 
} 

- (void)performCompleteEvent:(UIImage *)image { 
    //NSLog(@"RCPhoto finish loading"); 

    [self setImage:image]; 
    self.opaque = YES; 

    if ([delegate respondsToSelector:@selector(onPhotoComplete)]) { 
     [delegate performSelector:@selector(onPhotoComplete)]; 
    } 
} 


@end 

回答

2

dataWithContentsOfURL:被設計爲阻止,直到它超時或完成接收完整的響應。當關聯視圖被釋放時,您似乎有興趣中斷後臺線程。這些事實根本上是不一致的。

如果您希望在對象消失時儘快終止請求,可以通過在您的dealloc方法中使用NSURLConnectioncancel進行異步請求來完成此操作。如果在收到回覆之前未取消該回復,則會在您的代理人處回撥至connectionDidFinishLoading:,此時您可以從收到的數據中重組您的UIImage

+0

謝謝你,僅此而已。 – 2010-11-16 07:11:32

0

最終代碼:

- (void)loadImage:(NSString *)path { 
    imageData = [[NSMutableData data] retain]; 
    NSURL *url = [NSURL URLWithString: path]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
    connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES]; 
} 
- (void)connectionDidFinishLoading:(NSURLConnection *)conn { 
    UIImage *image = [[UIImage alloc] initWithData:imageData]; 
    [self setImage:image]; 
    self.opaque = YES;// explicitly opaque for performance 
    [image release]; 
}