2012-07-17 62 views
0

我試圖等待使用Restkit with Blocks的響應。iOS RestKit塊

例子:

NSArray *myArray = ["RESULT OF REST-REQUEST"]; 

// Working with the array here. 

我的一個塊的請求:

- (UIImage*)getPhotoWithID:(NSString*)photoID style:(NSString*)style authToken:(NSString*)authToken { 
__block UIImage *image; 
NSDictionary *parameter = [NSDictionary dictionaryWithKeysAndObjects:@"auth_token", authToken, nil]; 
RKURL *url = [RKURL URLWithBaseURLString:@"urlBase" resourcePath:@"resourcePath" queryParameters:parameter]; 
NSLog(@"%@", [url absoluteString]); 
[[RKClient sharedClient] get:[url absoluteString] usingBlock:^(RKRequest *request) { 
    request.onDidLoadResponse = ^(RKResponse *response) { 
     NSLog(@"Response: %@", [response bodyAsString]); 
     image = [UIImage imageWithData:[response body]]; 
    }; 
}]; 
return image; 
} 
+2

你的問題是什麼? – Till 2012-07-17 08:39:07

+0

該數組將爲null,因爲該方法在響應到達之前達到結束......我該如何「等待」響應。我認爲這將與塊 – Maik639 2012-07-17 10:03:40

回答

2

在此方法,因爲圖像的獲取將是異步的,就不能返回任何東西 - 它必須是-(void)

那麼,你會怎麼做?您應該將調用此方法的操作放入響應塊中。警惕區塊內的retain cycles

__block MyObject *selfRef = self; 

[[RKClient sharedClient] get:[url absoluteString] usingBlock:^(RKRequest *request) { 
    request.onDidLoadResponse = ^(RKResponse *response) { 

     NSLog(@"Response: %@", [response bodyAsString]); 

     image = [UIImage imageWithData:[response body]]; 

     [selfRef doSomethingWithImage:image]; 

    }; 
}]; 
+0

合作謝謝!這是一個很好的解決方案! – Maik639 2012-07-17 11:15:25

0

上面的代碼在打開ARC(XCode默認爲iOS 5.0以後)時不起作用。 __block變量不再免於在ARC下自動保留。在iOS 5.0及更高版本中使用__weak而不是__block來打破保留週期。