iOS監聽線程結束

#import "ViewController.h"
#define kPrintLog NSLog(@"%s isMain:%d",__func__,[NSThread isMainThread])
@interface ViewController ()

@end

@implementation ViewController
//arc也能出現dealloc
- (void)dealloc {
    //對象銷燬的時候 刪除 觀察者
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NSThreadWillExitNotification object:nil];
}

- (void)threadWillEnd:(NSNotification *)nf {
    kPrintLog;
    NSLog(@"obj:%@",nf.object);//誰發的通知
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    //每一個線程 結束的時候 都會發送一個NSThreadWillExitNotification的通知
    
    //首先 註冊一個觀察者對象 監聽線程 是否結束(線程只要把 相關的函數執行完就結束)
    //通知中心 內部會起一個子線程 專門監聽
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(threadWillEnd:) name:NSThreadWillExitNotification object:nil];
    
    kPrintLog;

    //若是 執行的是耗時的操做 咱們能夠 交給子線程來處理
    //不然的 耗時操做交給主線程來作 界面就有可能假死 影響用戶體驗
    //網絡下載數據 通常都是耗時的操做 網路下載數據 異步下載
    
    //建立三個子線程 來執行func1  func2 func3
    [NSThread detachNewThreadSelector:@selector(func1) toTarget:self withObject:nil];
    [NSThread detachNewThreadSelector:@selector(func2) toTarget:self withObject:nil];
    [NSThread detachNewThreadSelector:@selector(func3) toTarget:self withObject:nil];
    
}

- (void)func1 {
    kPrintLog;
    for (NSInteger i = 0; i < 10; i++) {
        NSLog(@"i:%ld",i);
        [NSThread sleepForTimeInterval:0.5];
    }
    NSLog(@"線程1即將結束");
}

- (void)func2 {
    kPrintLog;
    for (NSInteger i = 0; i < 10; i++) {
        NSLog(@"i:%ld",i);
        [NSThread sleepForTimeInterval:0.5];
    }
    NSLog(@"線程2即將結束");
}
- (void)func3 {
    kPrintLog;
    for (NSInteger i = 0; i < 10; i++) {
        NSLog(@"i:%ld",i);
        [NSThread sleepForTimeInterval:0.5];
    }
    NSLog(@"線程3即將結束");
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
相關文章
相關標籤/搜索