具有返回值的iOS块

我正在使用Facebook SDK中的一个块。 它返回一个字典。 我想把这个字典作为方法的返回值。 我试图把我的头围绕整个块的概念,但需要在正确的方向推动。

块:(块的参数是一个stringuserFBid)

-(NSDictionary*) getMutualFBFriendsWithFBid:(NSString*)fbID { [FBRequestConnection startWithGraphPath:[NSString stringWithFormat:@"/%@/mutualfriends/%@", [[PFUser currentUser] objectForKey:kFbID],userFBid] parameters:nil HTTPMethod:@"GET" completionHandler:^( FBRequestConnection *connection, id result, NSError *error ) { result = (NSDictionary*)result; //return result; }]; 

}

我如何得到返回值?

我试图谷歌它,但我不能让我的手在附近。

我将不胜感激指向正确的方向。

编辑:主要问题是:我需要完成处理程序调用另一个类中的方法…如何做到这一点?

由于startWithGraphPath是asynchronous的,所以你不能编码,就好像它是同步的:它意味着没有返回值,因为一旦这个方法被调用,你的应用程序将继续执行到下一行,并且不会等待一个返回的值。

所以,为了保持这种asynchronous,我假设你想在你自己的函数中使用这个结果,所以在你的completionHandler块中调用它:

 [FBRequestConnection startWithGraphPath:[NSString stringWithFormat:@"/%@/mutualfriends/%@", [[PFUser currentUser] objectForKey:kFbID],userFBid] parameters:nil HTTPMethod:@"GET" completionHandler:^(FBRequestConnection *connection, id result, NSError *error) { [self myRockinFunction:result]; }]; //Considering this function -(void)myRockinFunction:(NSDictionary*) fb_result{ //Do stuff with fb_result } 

编辑

好的我明白了。 修改你的方法来接受一个callback作为参数:

 -(NSDictionary*) getMutualFBFriendsWithFBid:(NSString*)fbID andCallback:(void (^)(NSDictionary *))callback { [FBRequestConnection startWithGraphPath:[NSString stringWithFormat:@"/%@/mutualfriends/%@", [[PFUser currentUser] objectForKey:kFbID],userFBid] parameters:nil HTTPMethod:@"GET" completionHandler:^(FBRequestConnection *connection,id result,NSError *error) { //You should treat errors first //Then cast the result to an NSDictionary callback((NSDictionary*) result); //And trigger the callback with the result }]; } 

然后,在其他class级中,使用另一个块来处理你的结果:

 [YourHelperClass getMutualFBFriendsWithFBid:fbID andCallback:^(NSDictionary* result){ //Use result how you wish //Beware, this is async too. }]; 

注意:您应该在触发callback之前处理错误。

编辑2(赞赏从其他用户的帮助)

更妙的是,你可能会尝试传递所有参数(未经testing,不确定语法,如果有人能纠正我,我会感激):

 -(NSDictionary*) getMutualFBFriendsWithFBid:(NSString*)fbID andCallback:(void (^)(FBRequestConnection *,NSDictionary *,NSError *))callback { [FBRequestConnection startWithGraphPath:[NSString stringWithFormat:@"/%@/mutualfriends/%@", [[PFUser currentUser] objectForKey:kFbID],userFBid] parameters:nil HTTPMethod:@"GET" completionHandler:callback()]; //Not sure here! } [YourHelperClass getMutualFBFriendsWithFBid:fbID andCallback:^(FBRequestConnection *connection,NSDictionary * result,NSError *error){ //You could deal with errors here now }]; 

这里有一个关于苹果公司文档的参考资料,以加深理解。

你已经有了:)

我会编写一个方法来处理字典,以使completionHandler块保持一点清洁 – 但是您可以在块内写入响应处理代码。 正如另一位评论者所说,这是asynchronous的,所以你并不真正“返回”任何东西……当它被调用时,你正在处理完成块。

为了帮助你理解一些,在这种情况下,completionHandler块是你传递给方法的一段代码作为参数,稍后再调用。 实质上,“每当这个呼叫回来,做这个:^ {”。 FBRequest方法的实现将会调用你的completionHandler(无论是什么)。