B-M*_*Man 7 facebook objective-c ios objective-c-blocks
我正在使用Facebook SDK中的一个块.它返回一个字典.我希望该字典作为方法的返回值.我试图围绕整个街区的概念,但需要在正确的方向轻推.
块:(块的参数是字符串userFBid)
-(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;
}];
Run Code Online (Sandbox Code Playgroud)
}
我如何获得返回值?
我试图谷歌它,但我无法抓住它.
我会很感激任何指针在正确的方向.
编辑: 主要问题如下:我需要完成处理程序来调用另一个类中的方法...如何做到这一点?
Big*_*ood 13
由于该方法startWithGraphPath
是异步的,您不能将其编码为同步:它意味着没有返回值,因为一旦调用此方法,您的应用程序将继续执行到下一行,并且不会等待返回值.
所以,为了保持这种异步,我假设你想在你自己的函数中使用它的结果,所以在你的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
}
Run Code Online (Sandbox Code Playgroud)
好的我明白了.修改您的方法以接受回调作为参数:
-(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
}];
}
Run Code Online (Sandbox Code Playgroud)
然后,在您的其他类中,使用另一个块来处理您的结果:
[YourHelperClass getMutualFBFriendsWithFBid:fbID andCallback:^(NSDictionary* result){
//Use result how you wish
//Beware, this is async too.
}];
Run Code Online (Sandbox Code Playgroud)
注意:您应该在触发回调之前处理错误.
更好的是,你可能会尝试传递一个带有所有参数的回调(没有经过测试,也不确定语法.如果有人可以纠正我,我会很感激):
-(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
}];
Run Code Online (Sandbox Code Playgroud)
以下是有关Apple更深入理解的文档的参考资料.
归档时间: |
|
查看次数: |
15958 次 |
最近记录: |