离开视图时停止异步块请求(AFNetworking; iOS)

时间:2014-06-19 22:53:14

标签: ios objective-c afnetworking objective-c-blocks nsoperation

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

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

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];

}

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

我的问题是,一旦我离开View Controller创建它们以节省内存和数据,或者如何正确处理它们,我该如何停止,取消或暂停这些过程? < / p>

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

感谢。

2 个答案:

答案 0 :(得分:1)

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

[operation cancel];

这可能属于ViewWillDisappear。

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

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

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

@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];
}

答案 1 :(得分:1)

事实证明,缺少停止源于一个计时器(称为块请求,或函数parse),一旦视图消失,它就不会失效。使-(void)viewDidDisappear:上的计时器失效解决了问题。