2011-10-09 68 views
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]; 

現在當了「自我」的對象dealloced之前完成的請求,會發生什麼的當然[self doSomeStuff];我的申請chrashes。

有沒有辦法取消這個塊請求釋放我的對象?

回答

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

+0

你是對的。我在我的完整塊中使用了一個類,我只將它分配給我的對象,此塊位於此處。保留這個類並在dealloc上釋放它現在工作正常。謝謝! – choise

+0

請注意,retainCount永遠不能返回0,並且不能用於證明對象在任何給定的持續時間內都保持可用。 – bbum

1

據我所見,您應該能夠撥打cancel停止操作。