gpt4 book ai didi

iphone - 停止从新线程加载照片

转载 作者:行者123 更新时间:2023-12-03 21:09:34 24 4
gpt4 key购买 nike

我正在使用此类加载图像。我需要有关如何在调用 dealloc 时阻止它们加载的帮助。该类扩展了 UIImageView。另外,对于设计类的任何其他建议,我都会表示赞赏,例如,我希望分派(dispatch)加载的字节。

@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

最佳答案

dataWithContentsOfURL: 被设计为阻塞,直到超时或完成接收完整响应。您似乎有兴趣在解除分配关联 View 时中断后台线程。这些事实从根本上来说是不一致的。

如果您想在对象消失时尽快终止请求,可以通过使用 NSURLConnection 发出异步请求并取消来完成在您的 dealloc 方法中。如果在收到响应之前没有取消,您将在委托(delegate)上收到对 connectionDidFinishLoading: 的回调,此时您可以根据收到的响应重新构建 UIImage数据。

关于iphone - 停止从新线程加载照片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4178688/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com