我第一次遇到这样的问题,需要你的帮助。
我正在获取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...
答案 0 :(得分: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
。
答案 1 :(得分:0)
您必须确保完成块在主线程上运行。
尝试以下代码..
dispatch_async(dispatch_get_main_queue(), ^{
testLabel.text=[NSString stringWithFormat: @"Hi ,%@",userID];
});