-1

For some reason I can't get twitterAccounts to hold another arrays data.

ViewController.h

@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

@property (strong, nonatomic) NSArray *twitterAccounts;
@property (strong, nonatomic) IBOutlet UITableView *chooseTwitterAccountTableView;

- (void)twitterRequest;

@end

ViewController.m

- (void)viewDidLoad
{
    [super viewDidLoad];

    _twitterAccounts = [[NSArray alloc]init];

    [self twitterRequest];

}

- (void)twitterRequest {

    ACAccountStore *account = [[ACAccountStore alloc]init];
    ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];

    [account requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error) {

        if (granted == YES) {

            NSArray *twitterAccountsTemp = [account accountsWithAccountType:accountType];

            _twitterAccounts = twitterAccountsTemp;

            NSLog(@"Array first has: %lu elements.", [_twitterAccounts count]);


        }

    }];

}

What I don't understand is if I have my viewDidLoad method like this:

- (void)viewDidLoad
{
    [super viewDidLoad];

    _twitterAccounts = [[NSArray alloc]init];

    [self twitterRequest];

    NSLog(@"After method called: %lu", [_twitterAccounts count]);

}

The output is:

After method called 0.
Array first has: 1 elements.

is it not supposed to be the other way around since I'm calling the method before outputting the amount of elements in the array?

Nathaly
  • 83
  • 1
  • 8

1 Answers1

1

requestAccessToAccountsWithType: is an asynchronous method, which means that it only initiates the request and returns. The completion block is called later, when the request has completed.

Therefore, after calling

[self twitterRequest];

the _twitterAccounts array has not yet been assigned to. When the request has finished and the completion block is called, _twitterAccounts = twitterAccountsTemp; is executed, and you can update the UI at that point, if necessary.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • is there a solution to get twitterAccounts to hold the data of twitterAccountsTemp? – Nathaly Dec 29 '13 at 22:21
  • @user3000730: Set a breakpoint at `NSArray *twitterAccountsTemp = ...`. You will see that the completion is called some time *later*. That's how asynchronous methods work, there is no way around it. – Martin R Dec 29 '13 at 22:24
  • ok thanks, my goal was to take the number of elements in that array and create a table view. so i needed the twitterAccounts array to hold it.. – Nathaly Dec 29 '13 at 22:28
  • @user3000730: You can update the table view from within the completion block (but on the main thread, see e.g. http://stackoverflow.com/a/18387414/1187415 for a similar issue). – Martin R Dec 29 '13 at 22:32