IPad crashes on orientation change

I am developing an iPad app. I accept both landscape and portrait mode. My UI is good in portrait mode, but when I change it to landscape mode my UI messes up. I saw some SO posts related to this and I added the following code to initWith ... in my UIView.

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

      

My UI works fine in portrait mode after that. When I change it to landscape mode, my UI is fine. But after I go back to portrait mode my app crashes. I read some posts on SO related to application crashing to learn about tools. I turned on zombies and found that a message is being sent to an already released object and this message is coming from the NSNotificationCenter.

Is there anything else I need to handle besides registering my device? Also, is there a way in which I can change the implementation from UIView to UIViewController and implement the methods that UIViewController has in regards to device orientation? Please let me know the steps I need to follow in order to do this. Thank!

+3


source to share


2 answers


Where do you register for notifications? You need to remove the observer when you are about to change the orientation (either in prepForSegue or AnimateRotationToInterfaceOrientation, whichever you have your setup) to prevent messaging with a more invalid object. You also don't want to accumulate multiple notifications if you register with viewDidAppear / viewWillAppear.

Remove the observer using:

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

      



or if you want to be specific, do something like:

[[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:[UIDevice currentDevice];//remove just that notification

      

+5


source


The class UIViewController

has several methods that deal with orientation changes. See the docs for a discussion of these methods.

One of the methods that you should learn is viewWillLayoutSubviews

. This is a common place to do manual view layout. This is called anytime the orientation of the controller changes.



Using these methods is much more common than registering for device orientation change notifications. Based on your glitch statements, the problem might be that you never remove the observer you add. For each call, there addObserver

must be a corresponding call removeObserver

. Otherwise, the observer is called even if it has long been gone. And this leads to a description of the accident.

0


source







All Articles