iOS Facebook的完成问题阻止

时间:2016-01-17 18:00:07

标签: ios objective-c facebook-graph-api objective-c-blocks

FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:@"/me/friendlists" 
                                                               parameters:@{ @"fields": @"name",} 
                                                               HTTPMethod:@"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
    if (!error)
        jsonArr1 = [result objectForKey:@"data"];

        //Inside the block
        for(int i=0; i<5; ++i)
            NSLog(@"%@", [[jsonArr1 objectAtIndex:i]objectForKey:@"name"]); //works fine
}]

//Outside the block
for(int i=0; i<5; ++i)
    NSLog(@"%@", [[jsonArr1 objectAtIndex:i]objectForKey:@"name"]); //gives out (null)

我发现这些块是异步调用的,这意味着只有在执行外部for循环后才调用该块,这就是为什么它在块外部给出null并在块内输出正常。

在块外使用jsonArr1是否有任何解决方法?我想在UITableView的tableView:cellForRowAtIndexPath方法中使用该数组。

有人可以帮忙吗?网上没有最新的教程可以将Fb集成到iOS中。

2 个答案:

答案 0 :(得分:0)

异步执行的全部意义在于您使用完成处理程序调用方法,该方法立即返回,同时调度要在其他队列上完成的实际工作,而不是调用它的回调处理程序。 strong>一旦方法的工作完成,结果就可以处理。

因此,处理完成处理程序中的数据。如果您需要更新UI,请执行以下操作:

C-q <

答案 1 :(得分:0)

    Is this correct?
    I did the way just you said but still it isn't working out!

     -(void) viewDidLoad
    {
    [request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {

    dispatch_queue_t aQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    dispatch_async(aQueue, ^{ 
    jsonArr = [result objectForKey:@"data"];
    for(int i=0; i<[jsonArr  count]; ++i)
    {
    [ultimateArr addObject:[[jsonArr objectAtIndex:i]objectForKey:@"name"]]; 
         //Don't know why but objects are not being added to the ultimateArr

    NSLog(@"%@", [[jsonArr objectAtIndex:i]objectForKey:@"name"]);
}
dispatch_async(dispatch_get_main_queue(), ^{
[myTableView reloadData];
                        });

                });

            }];

        }