tags:

views:

23

answers:

1

while reading cocoa fundamental guide i have gone through:

  • (void)addObserver:(id)notificationObserver selector:(SEL)notificationSelector name:(NSString *)notificationName object:(id)notificationSender

I am getting all theories, but actually i am looking for a real example where it is used ?

Can any one give some sample example.

Actually i want to send some notifications to observers when some event occurs.

and i also want to know how observer catch/handle/receive that notification ??

Thanks

+1  A: 

To listen for notifications, add code similar to this in the instance that you want to receive notifications:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(doThisWhenNotificationRecd:)
                                             name:@"SOME_NOTIFICATION_NAME" 
                                           object:nil]; 

When you want to post a notification:

[[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"SOME_NOTIFICATION_NAME" object:nil]];

I use code similar to this to update my UI while processing an in app purchase.

TomH
And if you were asking about how Key Value Observing is implemented under the hood, it is done through a technique called "isa swizzling". Whenever a message is sent to an object, the selector is passed to the class pointed at by the object's `isa` pointer. When you add a KVO to an object, the Obj-C runtime subclasses the object's class, creating a subclass that fires a notification when stuff is changed. It then reroutes the `isa` pointer to point to the custom subclass, yet keeps the `class` pointer deceitfully pointing to the object's nominal class.
Jon Rodriguez