NSNotification是IOS开发中的一种观察通知方法,相信很多文档中都介绍了它的用法,比我说得好。但是很多文档都忽视了它使用过程中导致崩溃的风险。
NSNotification风险主要来源于通知所注册的方法已经和VC一起移除。
通知中心注册:;
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(intoTrajectory) name:@"trajectory_into" object:nil];
当VC移除之后 不对通知中心注册的通知进行移除,当你再向通知中心发送执行此方法的信息就会导致程序崩溃。
发送执行通知注册的方法:
[[NSNotificationCenter defaultCenter]postNotificationName:@"trajectory_into" object:nil];
所以我们需要在ViewDidDisappear中remove这条通知
[[NSNotificationCenter defaultCenter]removeObserver:self name:@"trajectory_into" object:nil];
此外如果不及时remove注册的通知,再次进入此VC就会重复注册,当发送消息执行方法的时候会执行多次。