在已经释放的对象中取消阻止请求

时间:2011-10-09 11:21:13

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

所以我使用AFNetworking来处理使用Web服务的异步请求。

AFJSONRequestOperation *operation = [AFJSONRequestOperation operationWithRequest:request success:^(id JSON)
    {
        [self doSomeStuff];

    } failure:^(NSHTTPURLResponse *response, NSError *error)
    {
        XLog("%@", error);
    }];

    NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
    [queue addOperation:operation];

现在在请求完成之前释放“self”对象时会发生什么,当然我的应用程序在[self doSomeStuff];上崩溃了。

有没有办法在解除分配我的对象时取消这个块请求?

2 个答案:

答案 0 :(得分:1)

据我所知,你应该可以致电cancel来停止这项行动。

答案 1 :(得分:0)

我做了一些示例代码,结果会让您感兴趣。

我创建了一个创建请求的类:

@implementation Aftest
@synthesize name = _name;
- (void) doSomeStuff
{
    NSLog(@"Got here %@", self.name);
}

- (void)startDownload
{   
      self.name = [NSString stringWithFormat:@"name"];
      NSURL *requestURL = [NSURL URLWithString:@"http://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=twitterapi&count=2"];
      NSURLRequest *request = [NSURLRequest requestWithURL:requestURL];
      AFJSONRequestOperation *operation = [AFJSONRequestOperation operationWithRequest:request success:^(id JSON)
      {
           [self doSomeStuff];

      } failure:^(NSHTTPURLResponse *response, NSError *error)
      {
           NSLog(@"%@", [error localizedDescription]);
      }];

      NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
      [queue addOperation:operation];
}
@end

并称之为:

Aftest *af = [[Aftest alloc] init];
NSLog(@"1 - retain count %d", [af retainCount] );
[af startDownload];
NSLog(@"2 - retain count %d", [af retainCount] );
[af release];
NSLog(@"3 - retain count %d", [af retainCount] );

我得到的结果是:

2011-10-09 09:28:41.415 aftes[6154:f203] 1 - retain count 1
2011-10-09 09:28:41.418 aftes[6154:f203] 2 - retain count 2
2011-10-09 09:28:41.419 aftes[6154:f203] 3 - retain count 1
2011-10-09 09:28:43.361 aftes[6154:f203] Got here name

在块内传递时,应保留对象。它应该避免这些崩溃。

无论哪种方式,正如Micheal回答的那样,只要您有权访问操作对象,就应该可以调用cancel