开发者

cancel block request in already deallocated object

so i'm using AFNetworking for doing asynchronous requests with web-services.

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

now what happens when the "self" object is dealloced before the request finished is, that my application chrashes on [self doSomeStuff开发者_StackOverflow中文版]; of course.

is there a way to cancel this block-request when deallocating my object?


As far as I've seen, you should be able to call cancel to stop the operation.


I did some sample code and the result can interest to you.

I created a class that creates a request just like yours:

@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

And called this with:

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

The result that I got was:

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

Your object should be retained when passed inside the block. It should be avoiding these crashes.

Either way, as Micheal answered, it should be possible to call cancel as long as you have access to the operation object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜