Adding the Observer:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tapNewProduct:) name:@"TapNewProduct" object:nil];
You add the observer to "listen for things". The statement above is saying, "If you hear a TapNewProduct notification, then execute the method (selector) tapNewProduct
.
Posting Notifications to the Observer:
// This can be on a different viewController or the same viewController the
// observer lives
[[NSNotificationCenter defaultCenter] postNotificationName:@"TapNewProduct" object:self.productID];
You'd post a notification whenever you want the tapNewProduct
method (selector) to execute.
Removing the Observer:
This line posts the notification. You'd probably have this in didSelectRowAtIndexPath
, a UIButton
, or a UICollectionView
.
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"TapNewProduct" object:nil];
This line would go in dealloc
of the UIViewController
where you added the observer. When it's deallocated, the observer is removed.
Steps:
1) Add the observer first.
2) THEN you post the notification, which the observer picks up and then executes the selector you specified when you added the observer.
3) When you deallocate the class where you originally added the observer, you remove the observer (put it in dealloc
, not viewDidDisappear
).
See this answer for a more detailed explanation:
https://stackoverflow.com/a/2191802/4475605