13

AFNetworking を使用してサーバーからデータを取得しています。

-(NSArray)some function {
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
        success: ^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
            NSArray *jsonArray =[JSON valueForKey:@"posts"];
        }
        failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {}
}

ここでやろうとしているのは、jsonArray を関数に返すことです。明らかにリターンは機能していません。

4

3 に答える 3

3

他の人が言ったように、非同期呼び出しを扱うときはそれを行うことはできません。期待される配列を返す代わりに、完了ブロックをパラメーターとして渡すことができます

typedef void (^Completion)(NSArray* array, NSError *error);

-(void)someFunctionWithBlock:(Completion)block {
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
        success: ^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
            NSArray *jsonArray =[JSON valueForKey:@"posts"];
            if (block) block(jsonArray, nil);
        }
        failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) { 
            if (block) block(nil, error); 
        }
}

次に、そのsomeFunctionを呼び出す場所。このコードは、適切なエラー処理も行います。

[yourClassInstance someFunctionWithBlock:^(NSArray* array, NSError *error) {
   if (error) {
      NSLog(%@"Oops error: %@",error.localizedDescription);
   } else {
      //do what you want with the returned array here.
   }
}];
于 2015-08-01T23:25:48.820 に答える