继续得到无法分配的错误

时间:2015-01-05 18:53:17

标签: ios objective-c twitter

在下面的函数中,我一直得到:

  

变量不可分配(缺少__block类型说明符)

我尝试通过将__block添加到twitterUsername来修复它,但该函数返回null。我究竟做错了什么?我真的很想了解这背后的逻辑,而不仅仅是解决方案。

- (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;
}

1 个答案:

答案 0 :(得分:1)

requestAccessToAccountsWithType:options:completion:方法是异步的,这意味着它不会等待对网络调用的响应,并立即返回。 相反,它会在调用返回后将一个块排入队列,并在数据加载后执行它。

一种可能的解决方案是让你的getTwitterAccountInformation也将完成块作为参数,这可能如下所示:

- (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);
            }
        }
    }];
}
相关问题