如果我取消了操作中的NSInvocationOperation,对吗?示例:
.h文件:
//defined in the interface
NSInvocationOperation *op1;
NSOperationQueue *loadQueue;.m文件:
-(id)init{
op1 = [NSInvocationOperation new];
loadQueue = [NSOperationQueue new];
}
-(void)downloadData{
op1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(loadServerResponse:) object:newerRequest];
[loadQueue addOperation:op1];
}现在我有了从服务器下载数据的方法。我添加了一个条件来检查是否有错误。如果是这样的话,我将在方法中取消该操作,并在检索新的登录令牌时调用相同的方法。
- (void)loadServerResponse{
if(server_error){
[op1 cancel];
//fetch login token again
[self downloadData];
return;
}我做错什么了吗?
发布于 2014-09-09 05:35:23
首先,引用op1 (我假设它是一个类级ivar)是多个级别上的坏事™,第一个是NSOperationQueue将您的操作分派到后台线程,所以op1 (最多)将被复制到该线程的上下文中,不再引用您试图取消的原始操作。
考虑到您共享的逻辑,我认为您不需要担心取消操作。您似乎特别希望在取消操作后调用downloadData,如果您首先取消操作,则无法保证会发生这种情况。我会删除取消操作的电话,然后继续。通常,您只从外部源取消正在运行的操作(例如,如果收到应用程序将进入后台状态的通知)。
https://stackoverflow.com/questions/25735710
复制相似问题