2

我必须从服务器下载图像,但我不想创建 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];
}
4

2 回答 2

1

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

于 2012-10-01T05:28:32.177 回答
1

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

于 2012-10-01T05:28:40.640 回答