剛接觸ios開發半個月,對多線程的理解還很淺。今天做了一個簡單的需求,也記錄一下
在網上看到一個帖子,說ios平台實現多線程可以使用不同層級的API,有比較底層的NSThread,也有GCD等方式。我今天用的是performSelector方法
需求是在子線程裡進行耗時的操作(文件讀寫,上傳等),UI裡展示一個進度條,當子線程的任務完成,通知主線程關閉進度條(刷新UI)。以下是代碼:
主線程發起子線程調用:
-(void) listenLogoutStartEvent:(NSNotification*) notification
{
UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
indicator.center = self.view.center;
[self.view addSubview:indicator];
[indicator startAnimating];
[delegate performSelectorInBackground:@selector(doLogout) withObject:nil];
}-(void) doLogout
{
// 檢測網絡
// 備份
[backupDelegate doBackup];
// 向server發起注銷請求
// 清除本地登陸數據
[self clearLocalData];
// 通知MainViewController注銷完成
[[NSNotificationCenter defaultCenter] postNotificationName:LOGOUT_DONE object:self userInfo:nil];
}下面是ViewController裡偵聽事件的方法:
-(void) listenLogoutDoneEvent:(NSNotification*) notification
{
[self performSelectorOnMainThread:@selector(quitApp) withObject:nil waitUntilDone:NO];// 在quitApp方法中刷新UI
}從以上的示例代碼可以總結出2點:
1、在ios平台,用performSelectorOnMainThread和performSelectorInBackground方法,可以靈活地在主線程和子線程之間切換,而且API也很簡單,似乎是一種很好的方式
2、組件的方法本身不需要考慮線程,由調用者(一般是ViewController)來決定其執行的線程,是一種很好的模式