2

所以我使用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];当然会崩溃。

有没有办法在释放我的对象时取消这个块请求?

4

2 回答 2

1

据我所见,您应该可以调用cancel以停止操作。

于 2011-10-09T12:14:08.430 回答
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

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

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

于 2011-10-09T12:27:41.090 回答