2015-01-05 53 views
0

在下面的功能,我不斷收到:保持越來越不可分配錯誤

變量沒有分配(缺少__block類型說明符)

我試圖通過增加__blocktwitterUsername修復它,但隨後該函數返回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; 
} 
+5

您無法從這樣的異步方法返回任何東西;你的return語句在完成塊運行之前執行。 – rdelmar

回答

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