iOS内存管理进阶:detachNewThreadSelector与NSNotificationCenter

1、后台线程
iOS中启动线程是件很简单的事情,有多种方式,下面这种是我最喜欢的,不需要释放线程对象,线程结束自动释放线程。

[NSThread detachNewThreadSelector:SEL toTarget:self withObject:obj];


最近开发一个功能,需要在UIViewController中启动一个线程,target为UIViewController,
这时候联想到一个问题,如果点击navigationbar上的back按钮,这时候是否UIViewController会销毁,线程会引发程序崩溃?
搜索后得到下面的结论

The objects aTarget and anArgument are retained during the execution of the detached thread, then released.

同样适用的还有[self performSelectorInBackground]等接口。
target和object均会retain,线程结束后自动释放。

2、消息中心
同样挂在消息中心的观察者,如果观察者销毁了,必须在销毁之前从消息中心移除观察者。
在ARC中可能容易忘记这一点,ARC处理了大部分情况,以至于很多时候我们不需要实现dealloc方法。
但是消息中心是个特例,需要自己处理。

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

注意:arc中不需要写

[supre dealloc]

标签: iOS

添加新评论