Need help independently calling method: - (void) orientationChanged:(NSNotification *)note in iOS

StackOverflow https://stackoverflow.com/questions/14168852

  •  13-01-2022
  •  | 
  •  

Question

I'm writing an application that checks a device's orientation, and because of that, I have the following code block:

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

which in turn, calls the following method:

- (void) orientationChanged:(NSNotification *)note {
    ...
}

What I would like to do is call the above method separately from the initial code block that I posted from a separate section altogether. Is this possible, and if so, how?

Was it helpful?

Solution

What I usually do in this type of situation is pass nil as the argument:

[self orientationChanged:nil];

This depends on how critical the notification itself is to the implementation of the method. You may have to construct a notification with the appropriate information in it:

NSNotification *n = [NSNotification notificationWithName:@"someName" object:someObject];
[self orientationChanged:n];

However, I have come to view this type of need as a code smell, what I try to do instead is extract the work the notification handler performs into a separate method and call that one directly, e.g.:

- (void)handleOrientationChangeForDevice:(UIDevice *)d {
    // do something here
}

- (void)orientationChanged:(NSNotification *)n {
    [self handleOrientationChangeForDevice:n.object];
}

Then, in the calling code, you could do something like:

[self handleOrientationChangeForDevice:[UIDevice currentDevice]];

OTHER TIPS

If you need the device's orientation without waiting for the Notification, you can just get it this way:

UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;

You can call it by passing nil parameter or whatever object of type NSNotification you want to pass like

To call it in .m of same class-

[self orientationChanged:nil];

To call from another class-

[controller orientationChanged:nil]; //Declare method in .h first
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top