2013-03-05 30 views
1

我遇到了這樣的問題,第一次,需要你的幫助。顯示標籤或textview上的文字需要更多時間,而它正在顯示的控制檯

我抓取twitter用戶信息和NSLog我可以在控制檯中看到它,但是當我在標籤或文本視圖上顯示它時,需要更多時間,差不多1分鐘。

我使用的代碼是....

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

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

      // Request access from the user to use their Twitter accounts. 

      { 
       // Did user allow us access? 
       if (granted == YES) 
       { 
        // Populate array with all available Twitter accounts 
        NSArray *arrayOfAccounts = [_accountStore accountsWithAccountType:accountType]; 
        [arrayOfAccounts retain]; 

        // Populate the tableview 
        if ([arrayOfAccounts count] > 0) 
         NSLog(@"print %@",[arrayOfAccounts objectAtIndex:0]); 
        // 
        ACAccount *twitterAccount = [arrayOfAccounts objectAtIndex:0]; 

        NSString *userID = [[twitterAccount valueForKey:@"properties"] valueForKey:@"user_id"]; 
        NSLog(@"print user id is %@",userID);// Here i can see immediately 

        testLabel.text=[NSString stringWithFormat: @"Hi ,%@",userID];// Here it is taking more time... 

回答

2

您正在從異步線程更新UI元素。這就是問題發生的原因。

替換:

testLabel.text=[NSString stringWithFormat: @"Hi ,%@",userID]; 

有了:

dispatch_sync(dispatch_get_main_queue(), ^{ 

    testLabel.text=[NSString stringWithFormat: @"Hi ,%@",userID]; 

}); 

記住:你應該更新只從主線程的UI元素。

在你的情況下,你在block裏面寫了代碼,塊將在異步線程中執行,而不是在主線程中。您正在更新您的UI元素。這將導致此問題,因此您需要從主線程更新UI,因爲您使用的是dispatch_get_main_queue

+0

感謝Midhun ..它解決了這個問題,但你可以請詳細描述它。 – Sawant 2013-03-05 05:56:11

+0

@Sawant:很高興:)請記住**從主線程更新UI元素只有** – 2013-03-05 06:12:42

+0

@Sawant:增加更多細節 – 2013-03-05 06:17:47

0

您必須確保完成塊在主線程上運行。

試試下面代碼..

dispatch_async(dispatch_get_main_queue(), ^{ 
    testLabel.text=[NSString stringWithFormat: @"Hi ,%@",userID]; 
});