iOS_某操作霸占主线程过久导致“界面假死”的一种解决方法

http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Multithreading/Introduction/Introduction.html#//apple_ref/doc/uid/10000057i-CH1-SW1

/*首先往消息中心注册一个检测针对的observer。*/
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleResult:) name:@"PostNO." object:nil];

/*然后创建一个线程做之前耗时过久的操作。*/
[NSThread detachNewThreadSelecto:@selector(calculate) toTarget:self withObject:nil];

/*耗时的操作*/
- (void)caculate
{
    /*新建的线程必须创建自己的内存释放池!*/
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSString *result = @"1111";
    /*事情做完后告知消息中心*/
    [[NSNotificationCenter defaultCenter] postNotificationName:"PostNO." object:result];
    [pool release];
}
/*耗时操作执行完后的回调函数*/
- (void)handleResult:(NSNotification *)noti
{
    id obj = [noti object];
    [self performSelectorOnMainThread:@selector(getResult:) withObject:obj waitUtilDone:YES];
}
/*在主线程进行的操作*/
- (void)getResult:(id)result
{
    //do some thing(更新UI界面之类的)
}

 记得结束后,把observer从NSNotificationCenter 中remover掉

转载于:https://www.cnblogs.com/kelisi-king/p/3223727.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值