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


转载于:https://my.oschina.net/u/2410306/blog/529410

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值