开发者

stopping a photo from a new thread to load

I'm loading images with this class. I need help on how to stop them from loading when dealloc is called. This class is extending UIImageView. Also any other advice for designing the class is appreciated, i'll want for example to dispatch the loaded bytes.

@imp开发者_C百科lementation 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


dataWithContentsOfURL: is designed to block until it times out or finishes receiving a complete response. You seem interested in interrupting the background thread when its associated view is deallocated. These facts are fundamentally at odds.

If you want to terminate the request as quickly as possible when your object is going away, this can be done by making an asynchronous request with NSURLConnection and canceling it in your dealloc method. If it isn't canceled before the response is received, you'll get a callback to connectionDidFinishLoading: on your delegate, at which point you can reconstitute your UIImage from the received data.


Final code:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜