不断出现不可分配的错误



在下面的函数中,我不断得到:

变量不可分配(缺少__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;
}

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);
            }
        }
    }];
}

最新更新