gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 19:52:37 24 4
gpt4 key购买 nike

我在我的应用程序中使用 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, NSHTTPURLResponse *response, NSError *error, id JSON) {

//operation failed

}];

最佳答案

在对 AFNetworking 源代码进行了整整一个上午的挖掘之后,事实证明我的操作没有取消的原因与操作本身无关,而是因为我一直以来都在错误地启动操作。我一直在用

[NSOperation start];

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

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

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

关于objective-c - 如何使用 AFNetworking 立即强制取消 NSOperation?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12361824/

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