塊內函數的返回值我正在使用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返回給函數。顯然退貨是行不通的。
3 回答

慕姐8265434
TA貢獻1813條經驗 獲得超2個贊
您不能使用完成塊為您的方法創建返回值。在AFJSONRequestOperation
異步執行其工作。someFunction
在操作仍在進行時將返回。成功和失敗模塊是您在需要的地方獲得結果值的方式。
這里的一種選擇是將調用者作為參數傳遞給包裝方法,以便完成功能塊可以傳遞數組。
- (void)goFetch:(id)caller{ AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success: ^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { [caller takeThisArrayAndShoveIt:[JSON valueForKey:@"posts"]]; } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {}}
您還可以使調用者創建并傳遞一個成功運行的阻止程序。然后,goFetch:
不再需要知道調用者上存在哪些屬性。
- (void)goFetch:(void(^)(NSArray *))completion{ AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success: ^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { if( completion ) completion([JSON valueForKey:@"posts"]); } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {}}

一只名叫tom的貓
TA貢獻1906條經驗 獲得超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. }}];

Qyouu
TA貢獻1786條經驗 獲得超11個贊
我遇到了此類問題,并通過以下方法解決了。我看到了以上使用塊的答案。但是此解決方案當時更適合。該方法的邏輯很簡單。您需要將對象及其方法作為參數發送,請求完成后將調用該方法。希望能幫助到你。
+(void)request:(NSString *)link parameters:(NSDictionary *)params forInstance:(id)instance returns:(SEL)returnValue{ AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; [manager GET:link parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) { [instance performSelector:returnValue withObject: responseObject]; } failure:^(AFHTTPRequestOperation *operation, NSError *error) { [instance performSelector:returnValue withObject:nil]; //NSLog(@"Error: %@", error); }];}
- 3 回答
- 0 關注
- 450 瀏覽
添加回答
舉報
0/150
提交
取消