这是从后台线程访问UI工具包的安全方式吗?

时间:2012-10-01 05:04:56

标签: iphone objective-c ios uikit

我必须从服务器下载图像,但我不想创建NSURLConnection,我知道UIKit不是线程安全的所以我试过这个,只需要确认这是否安全或是否会导致崩溃(截至目前它工作正常。)我尝试了以下

查看开关的案例2.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  switch (indexPath.row) {
    case 0:
    {
      CreateNewSurveyViewController *vc=[[CreateNewSurveyViewController alloc] init];
      [self.navigationController pushViewController:vc animated:YES];
      [vc release];
      break;
    }
    case 1:{
      MySurveyViewController *mySurveyViewController=[[MySurveyViewController alloc] init];
      [self.navigationController pushViewController:mySurveyViewController animated:YES];
      [mySurveyViewController release];
      break;
    }
    case 2:{

        self.progressHud.hidden = NO;
        [self performSelectorInBackground:@selector(loadProfileImage) withObject:nil];
      break;
    }
    default:
      break;
  }
}   
-(void)loadProfileImage {

    NSData* profileImageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.userAccount.profileImageURL]];
    [self performSelectorOnMainThread:@selector(launchSettingsView:) withObject:profileImageData waitUntilDone:YES];

}

-(void)launchSettingsView:(NSData*)profileImageData {
    self.userAccount.userImage = [UIImage imageWithData:profileImageData];
    self.progressHud.hidden = YES;
    SettingsViewController* settingsViewController=[[SettingsViewController alloc] init];
    settingsViewController.userAccount = self.userAccount;
    settingsViewController.delegate = self;
    [self.navigationController pushViewController:settingsViewController animated:YES];
    [settingsViewController release];
}

2 个答案:

答案 0 :(得分:1)

这对我来说很安全。您在后台线程上执行所有网络连接,然后只触摸您回调的主线程方法中的UI。通常人们会使用GCD或NSOperationQueue,但这也应该有用。

答案 1 :(得分:1)

只要实际的UI更新工作在主线程上完成,你就可以了。