AaronTry
AaronTry

Reputation: 53

Can't retrieve data outside startWithCompletionHandler

I am putting Facebook user information data into an NSMutableArray, I am doing it using an for loop inside a request method call. The problem is I can't get data outside the method call. The first self.items in NSLog can show the data I want, which contains all the full names I put. However, the second self.items in NSLog is an empty NSMutableArray.

in .h file:

@property (strong,nonatomic) NSMutableArray *items;

Initialized array:

self.items = [[NSMutableArray alloc] init];

Here is my code:

- (IBAction)reloadFriendList:(id)sender {

    FBRequest *request = [FBRequest requestForMyFriends];
    [request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
        NSString *space = @" ";
        for (id<FBGraphUser> user in result[@"data"]) {
            NSArray *array = [[NSMutableArray alloc] initWithObjects:[user first_name], space, [user last_name], nil];
            NSString *fullName = [array componentsJoinedByString:@""];
            [self.items addObject:fullName];
        }
        NSLog(@"%@",self.items);
    }];
    NSLog(@"%@",self.items);
}

Could anybody tell me what's going on? Thank you!

Upvotes: 0

Views: 245

Answers (2)

rocky
rocky

Reputation: 3541

I don't think you fully understand what is happening here. The completion handler block is executed when the request completes, while the NSLog statement after the completion handler block is executed right after you call [request startWithCompletionHander...]. So here are the events in chronological order:

  1. You call [request startWithCompletionHandler...]
  2. The NSLog outside the block is executed (self.items should be empty since the request has not completed)
  3. Once the request completes at some arbitrary time later, the completion handler block is executed and your self.items is filled and the NSLog then prints out all items (which should be non-empty if items were actually in the response).

Upvotes: 3

rmaddy
rmaddy

Reputation: 318874

The handler is asynchronous so the log message outside the call is made long before you get the data.

Upvotes: 2

Related Questions