2012-10-01 45 views
2

我不得不從服務器上下載圖片,但我不想創建NSURLConnection,我知道UIKit不是線程安全的,所以我試過了,只需要確認一下,如果這是安全的還是會導致崩潰截至目前它工作正常。)我試過以下這是從後臺線程訪問UI工具包的安全方式嗎?

看看交換機的情況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]; 
} 

回答

1

這對我來說看起來很安全。你可以在後臺線程上完成所有的網絡連接,然後只用你回叫的主線程方法觸摸UI。通常人們會使用GCD或NSOperationQueue,但這也應該起作用。

+0

我通常使用GCD,但我的客戶希望支持ios 3.2及以上版本,因此GCD無法使用。 –

+1

@AnkitSrivastava你的客戶有不合理的期望! – jrturton

+0

@jrturton我知道......但客戶永遠是對的。 –

1

只要在主線程上完成實際的UI更新工作,你就會好起來的。