gpt4 book ai didi

ios - 离开 View 时停止异步 block 请求(AFNetworking;iOS)

转载 作者:行者123 更新时间:2023-11-28 22:04:39 25 4
gpt4 key购买 nike

我正在使用 AFNetworking (2.3.1) 解析 JSON 数据并将其显示在标签中。

为此,我使用了在 AFHTTPRequestOperation.h 中声明的 setCompletionBlockWithSuccess

viewDidLoad 上调用了三个这样的函数,其中一个看起来像:

-(void)parse {

NSURL *url = [[NSURL alloc] initWithString:kURL];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

NSLog(@"Parse Successful");
//Code for JSON Parameters and to display data


} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

NSLog(@"%@", [error localizedDescription]);
//Code for Failure Handling

}];

[operation start];

}

虽然这就像一个魅力,因为它被包含在一个 block 请求中,这个过程在整个应用程序状态中继续。因此,当不需要显示此数据时,请求仍在加载,并且由于这些 block ,我收到了内存警告。

我的问题是,一旦我离开创建这些进程的 View Controller ,我该如何停止、取消或暂停这些进程,以节省内存和数据,或适本地处理它们?

如果这是一个明显的答案,请原谅我,我只是以完全错误的方式处理或创建 block 。我对 AFNetworking 和 block 、操作、异步请求等都是新手。

谢谢。

最佳答案

假设您有一个名为 operation 的 AFHTTPRequestOperation 对象:

[operation cancel];

这可能属于 ViewWillDisappear。

然后在您的失败 block (随后将被调用)中,您可以检查它是否因错误而失败,或者您是否取消了它:

if ([operation isCancelled])
{
//I canceled it.
}

更新 - 一个更具体的示例,说明如何保存对操作的引用并在 View 消失时取消它。

@interface myViewController ()

@property (strong, nonatomic) AFHTTPRequestOperation *parseOperation;

@end

@implementation myViewController

- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];

//no need to check to see if the operation is nil (because it never happened or it's complete) because
//messages sent to nil are ok.
[self.parseOperation cancel];
}

-(void)parse {

NSURL *url = [[NSURL alloc] initWithString:kURL];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

//save the parse operation so we can cancel it later on if we need to
self.parseOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
self.parseOperation.responseSerializer = [AFJSONResponseSerializer serializer];

__weak myViewController *weakSelf = self;
[self.parseOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//nil out the operation we saved earlier because now that it's finished we don't need to cancel it anymore
weakSelf.parseOperation = nil;

NSLog(@"Parse Successful");
//Code for JSON Parameters and to display data


} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (!operation.isCancelled) {
NSLog(@"%@", [error localizedDescription]);
//Code for Failure Handling
}
}];

[self.parseOperation start];
}

关于ios - 离开 View 时停止异步 block 请求(AFNetworking;iOS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24317481/

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