2

そのため、Webサービスで非同期リクエストを実行するためにAFNetworkingを使用しています。

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

ブロック内を通過するときにオブジェクトを保持する必要があります。これらのクラッシュを回避する必要があります。

いずれにせよ、Michealが答えたようcancelに、操作オブジェクトにアクセスできる限り、呼び出すことができるはずです。

于 2011-10-09T12:27:41.090 に答える