iPad App因方向改变而崩溃

use*_*519 3 objective-c nsnotificationcenter device-orientation ios

我正在开发一款iPad应用程序.我同时允许横向和纵向模式.我的UI在纵向模式下很好,但当我将其更改为横向模式时,我的UI变得混乱.我看到了一些与此相关的SO帖子,我在initWith中添加了以下代码...在我的UIView中.

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(abc)
                                             name:UIDeviceOrientationDidChangeNotification
                                           object:nil];
Run Code Online (Sandbox Code Playgroud)

这样做后,我的UI在纵向模式下工作正常.当我将其更改为横向模式时,我的用户界面很好.但在我将其更改回纵向模式后,我的应用程序崩溃了.我读了一些与应用程序崩溃相关的SO有关仪器的帖子.我启用了僵尸,发现正在向已发布的对象发送消息,此消息来自NSNotificationCenter.

除了注册我的设备之外,还有什么我需要处理的吗?另外,有什么方法可以将实现从UIView更改为UIViewController并实现UIViewController有关设备方向的方法?请让我知道我需要遵循的步骤才能完成这项工作.谢谢!

Tom*_*voy 5

你在哪里注册通知?当您即将更改方向时,您需要删除观察者(在prepForSegue或willAnimateRotationToInterfaceOrientation中,具体取决于您的设置),以防止消息传递不再有效的对象.如果您在viewDidAppear/viewWillAppear中注册,您也不希望堆积多个通知.

使用以下方法删除观察者:

[[NSNotificationCenter defaultCenter] removeObserver:self];//removes all notifications for that object (the way I've used it before)
Run Code Online (Sandbox Code Playgroud)

或者如果您想要具体,请执行以下操作:

[[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:[UIDevice currentDevice];//remove just that notification
Run Code Online (Sandbox Code Playgroud)