#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