加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

objective-c – 如何使用AFNetworking立即强制取消NSOperation?

发布时间:2020-12-16 10:22:55 所属栏目:百科 来源:网络整理
导读:我在我的应用程序中使用AFNetworking,我正在尝试在我的进度HUD中实现“点按取消”功能.我有一个管理所有HTTP请求的单例类.如果点击进度HUD,我打电话: [[[HTTPRequestSingleton sharedClient] operationQueue] cancelAllOperations]; 但这并不像我需要的那样
我在我的应用程序中使用AFNetworking,我正在尝试在我的进度HUD中实现“点按取消”功能.我有一个管理所有HTTP请求的单例类.如果点击进度HUD,我打电话:

[[[HTTPRequestSingleton sharedClient] operationQueue] cancelAllOperations];

但这并不像我需要的那样“取消”操作.我读了NSOperationQueue docs并发现了这个:

Canceling an operation object leaves the object in the queue but notifies the object that it should abort its task as quickly as possible. For currently executing operations,this means that the operation object’s work code must check the cancellation state,stop what it is doing,and mark itself as finished. For operations that are queued but not yet executing,the queue must still call the operation object’s start method so that it can processes the cancellation event and mark itself as finished.

关于cancelAllOperations方法:

This method sends a cancel message to all operations currently in the queue. Queued operations are cancelled before they begin executing. If an operation is already executing,it is up to that operation to recognize the cancellation and stop what it is doing.

我的问题似乎特别涉及一个已经执行的操作,我想立即取消.使用AFNetworking,如何提醒操作它应该取消并丢弃有关请求的所有信息?

用于操作的代码

AFJSONRequestOperation *loginOperation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request,NSHTTPURLResponse *response,id JSON) {

    //operation was successful

    if (loginOperation.isCancelled)
    {
        //can't do this. variable 'loginOperation' is uninitialized when captured by block      
    }

} failure:^(NSURLRequest *request,NSError *error,id JSON) {

    //operation failed

}];

解决方法

经过一整天的AFNetworking源代码挖掘后,事实证明我的操作没有取消的原因与操作本身无关,而是因为我一直在错误地开始操作.我一直在用

[NSOperation start];

当我应该将它添加到我的HTTPRequestSingleton的操作队列时:

[[[HTTPRequestSingleton sharedClient] operationQueue] addOperation:NSOperation];

将其添加到队列可以正确取消它,而无需检查isCancelled属性.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读