user4334509
user4334509

Reputation: 125

Keep getting unassignable error

In the function below, I keep getting:

Variable is not assignable (missing __block type specifier)

I tried fixing it by adding __block to twitterUsername, but then the function returns null. What am I doing wrong? I would really like to understand the logic behind this, not just a solution.

- (NSString *) getTwitterAccountInformation
{
    ACAccountStore *accountStore = [[ACAccountStore alloc] init];
    ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];

    NSString *twitterUsername = [[NSString alloc] init];

    [accountStore requestAccessToAccountsWithType:accountType 
                                          options:nil 
                                       completion:^(BOOL granted, NSError *error) 
    {
        if(granted) {
            NSArray *accountsArray = [accountStore accountsWithAccountType:accountType];

            if ([accountsArray count] > 0) {
                ACAccount *twitterAccount = [accountsArray objectAtIndex:0];
                NSLog(@"%@",twitterAccount.username);
                NSLog(@"%@",twitterAccount.accountType);

                twitterUsername = [NSString stringWithFormat:@"%@", twitterAccount.username];
            }
        }
    }];

    NSLog(@"Twitter username is: %@", twitterUsername);

    return twitterUsername;
}

Upvotes: 0

Views: 66

Answers (1)

David Ganster
David Ganster

Reputation: 1993

The requestAccessToAccountsWithType:options:completion: method is asynchronous, meaning it doesn't wait for a response to the network call, and returns immediately. Instead, it enqueues a block for execution once the call has returned, and executes it once the data has been loaded.

A possible solution is to make your getTwitterAccountInformation also take a completion block as an argument, which might look like this:

- (void) getTwitterAccountInformation:(void(^)(NSString *userName, NSError *error))completion
{
    ACAccountStore *accountStore = [[ACAccountStore alloc] init];
    ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];

    [accountStore requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error) {
        if(error) {
             completion(nil, error);
        }
        if(granted) {
            NSArray *accountsArray = [accountStore accountsWithAccountType:accountType];

            if ([accountsArray count] > 0) {
                ACAccount *twitterAccount = [accountsArray objectAtIndex:0];
                NSLog(@"%@",twitterAccount.username);
                NSLog(@"%@",twitterAccount.accountType);

                NSString *twitterUsername = twitterAccount.username;
                NSLog(@"Twitter username is: %@", twitterUsername);
                completion(twitterUsername, nil);
            }
        }
    }];
}

Upvotes: 1

Related Questions