Love to be Notified! @ Dr. Touch. Good introduction to Notifications. Notifications are great, similar to a Publish/Subscribe network setup inside your application. However, Notifications are so cool, you may be tempted to over use them. Most cases your app will only have a single Object that actually cares about notifications. In this case, NSNotifications would be overkill and cost more than it saves, use Delegates.
Friendly reminder. If you register for a notification with the notification center, you must unregister on dealloc. If our object goes away, but is still registered to receive notifications, your application will crash.
Matt Gallagher has a good write-up on multi-threaded code and design with Cocoa. He makes good use of NSOperation and NSNotificationCenter for managing communication. One of the key aspects is handover. That is, one specific operation occurs on a single bit of data at a time (that data is not operated on by another thread until the operation is complete). This requires clean design (a good thing) and a clear understanding how a data’s lifetime. While reading the article I was trying to come up with situations where data needed to operated on simultaneously and can’t really think of a good example that a good design would handle (other than complex clustered server architectures).
I’m working on an application that requires switching from a List View in portrait mode into a Cover Flow View when the device is rotated into landscape mode. This means, a Controller needs to know when a rotation has occurred and present the correct view. This was my first opportunity to play with Notifications.
- The Device generates these notifications on request. So, the first thing we need to do is tell it to start generating them.
- The Controller has to register to listen for these events.
- A Selector is provided as a callback when an event occurs.
Here is the code snippet that manages this:
- (void)viewDidLoad {
[super viewDidLoad];
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(deviceDidRotate:)
name:@"UIDeviceOrientationDidChangeNotification"
object:nil];
}
- (void)deviceDidRotate:(NSNotification *)notification {
UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
if (orientation == UIDeviceOrientationLandscapeLeft ||
orientation == UIDeviceOrientationLandscapeRight)
{
NSLog(@"Sideways");
} else {
NSLog(@"Portrait");
}
}