groups

Link to this snippet:


Download to Code Collector

language: Objective-C
licence: Other

NSNotifications template

options: send to code collectorview all willc2's snippets
// used for interclass communication, especially auxillary view controllers passing status info to their parent to update UI
// SEE ALSO: NSNOTIFICATIONS

// calling class can see it

// declare extern in header if calling externally, else just put string in .m file
#pragma mark -
#pragma mark Notifications
#pragma mark Notification Constant Keys
extern NSString *WCClassEventNotification;
#pragma mark -
NSString *WCClassEventNotification = @"class subject verb"; // WCTimerViewTitleDidChangeNotification = @"timerView title didChange"
#pragma mark -

#pragma mark -
#pragma mark Notification Posting
[[NSNotificationCenter defaultCenter] postNotificationName:WCClassEventNotification object:self]; // use self so message can be distinguished by instance

// import header of poster into listener first
#pragma mark Notification Listener Setup
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(someMethod:) name:WCClassEventNotification object:nil];

#pragma mark Notification Listener Teardown
[[NSNotificationCenter defaultCenter] removeObserver:self name:WCClassEventNotification object:nil];

#pragma mark Observer Method
// action method must take one and only one parameter, a notification
-(void) doSomething:(NSNotification *)notification;
{	
	NSObject *obj = [notification object]; // check for correct payload if it may vary
	
	if ([obj isKindOfClass:[NSString class]]) { // in this case the right payload is a NSString
		// if correct kind of payload is detected, then do stuff
	} else {
		// check for another kind of object or error condition 
	}
}