【发布时间】:2014-04-07 09:31:23
【问题描述】:
我正在寻找解决以下问题的解决方案:
我有一个在后台下载图像的 NSOperation:
@protocol CoreImageDownloadingOperationDelegate <NSObject>
@required
-(void) handleResponse:(UIImage*) response;
-(void) handleException:(MobileServiceException*) exception;
@end
@interface CoreImageDownloadingOperation : NSOperation{
}
-(id) initWithDelegate:(id<CoreImageDownloadingOperationDelegate>)del andImageID: (NSString *) image;
@property (nonatomic, assign) id <CoreImageDownloadingOperationDelegate> delegate;
下载完成后,调用委托方法,将图片设置为imageView:
pragma mark - overridden from NSOperation
- (void) main {
if (self.isCancelled)
return;
@autoreleasepool {
@try {
UIImage* image = [[CoreEnvironment sharedInstance] getImageFromServer: [imageID stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
if (self.isCancelled)
return;
if(delegate){
[delegate handleResponse:image];
}
else
NSLog(@"CachedImageView already deallocated");
}@catch (NSException *exception) {
TestLog(@"%@", exception.reason);
if (self.isCancelled)
return;
if(delegate && [exception isKindOfClass:[MobileServiceException class]])
[delegate handleException:(MobileServiceException*)exception];
}
}
}
问题是:当我在图像下载时转到另一个页面时,cachedImageView 被释放,但是当 imageDownloadingOperation 完成下载时,委托不是 nil,它正在尝试处理响应......当然我得到了消息发送到 deallocated...
我在CachedImageView中alloc初始化这样的操作:
CoreImageDownloadingOperation* imageDownloadingOperation = [[CoreImageDownloadingOperation alloc] initWithDelegate:self andImageID:imageKey];
或:
-[CachedImageView isKindOfClass:]: message sent to deallocated instance 0x18868550
【问题讨论】:
-
将assign属性替换为weak
-
我没用ARC,所以不能用weak
-
有很多框架可以异步加载图片。以 SDWebImage 为例。
-
weak 和 assign 是相同的,在 ARC 项目中使用 weak 但它们的数量相同。您的协议声明在哪里?
-
我用协议声明更新了我的问题
标签: ios memory-management delegates nsoperation dealloc