iOS - Using dealloc to remove observer - ios

I have a basic question regarding removing observer.
I have a ViewController parent class which is inherited by 3 ViewController child classes.
eg. BookVC -> BookHotelVC, BookFlightVC, BookTrainVC
Here, I added an observer in the viewDidLoad of parent class (I do [super viewDidLoad] in child ViewControllers) which notifies a method written in parent class. My code-
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(BookingCompleted:) name:#"BookingCompleted" object:nil];
Now I want to remove the observer when I move away from any of the child ViewControllers, but I can't write [super dealloc] in dealloc of each child ViewController because ARC doesn't permit this.
How can I remove the observer which is set ? Because whenever I move to child ViewController, a new observer is added which causes weird things (like, calling that method twice/thrice... - invoking alert twice/thrice...).
Kindly suggest.

Removing the observers in dealloc is fine, do not call [super dealloc] (as you saw, with ARC enabled, the compiler won't let you), simply write:
- (void)dealloc {
[self removeYourObservers];
}

Just don't call super! In ARC it's not required (see http://clang.llvm.org/docs/AutomaticReferenceCounting.html#dealloc).
-(void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}

Related

Where to remove observer for NSNotificationCenter in Objective-C

I dont want to add observer in viewDidAppear and remove in viewDidDisappear.Will not serve my case.
I have tried doing it in dealloc.
My root VC is in navController.Then a second VC is pushed in navController, where I addObserver for notifications to be sent from rootVC.The problem is when I pop the secondVC its dealloc is not called immediately or may be somtimes not called alltogether.
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(newMessagesNotification:) name:_newMessageNotificationListenerName object:nil];
}
- (void)newMessagesNotification:(NSNotification *)notification {
//some implementation
}
If you do not want to remove in the ViewDidDisapear than i think you should remove it right after you called the navigationCotnroller pop methode. But I think we can't tell you the exact moment when you should remove because we don't know when you want to remove it and why it isn't good in the ViewWillDisapier or in the ViewDidDisapier.

Issue while calling NSNotificationCenter

I want to call a method from another class via NSNotificationCenter.Everything is working fine.
The problem is my method called up two times.
ViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(removeAllSubViews:) name:#"getTheRequest" object:nil];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)removeAllSubViews:(NSNotification *)notification
{
NSLog(#"%#",notification.object);
NSLog(#"Print");
}
ViewController2.m
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] postNotificationName:#"getTheRequest" object:#"mySite"];
// Do any additional setup after loading the view.
}
When I run, I get this in console:
Why my method is called up two times ?
Edit
When I use this code in ViewController2.m it works fine. But Why?? **
[[NSNotificationCenter defaultCenter] removeObserver:self name:#"getTheRequest" object:nil];
You have to remove observer after use of it inside the method.
- (void)removeAllSubViews:(NSNotification *)notification
{
[[NSNotificationCenter defaultCenter] removeObserver("getTheRequest")]
NSLog(#"%#",notification.object);
NSLog(#"Print");
}
I've seen this before when I had a retain cycle in my view controller, so every time a instance of this view controller was created, it was added as an NSNotificationCenter observer, but because of the retain cycle when the view controller was dismissed, it was never actually deallocated/released from memory, so technically it was still an observer.
You might want to try to add the following to your view controller:
- (void)dealloc {
NSLog(#"Dealloc called.");
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
This should remove your view controller as an observer when it is dismissed, if there is no retain cycle, and if there is the NSLog will never be called - which is indicative of a larger memory-related issue, where what you're seeing is just a side-effect.
You are probably seeing multiple calls to that method, because you register the observer multiple times (e.g. you have navigated to that view controller before), but did not remove it again at the appropriate places. Anyways, viewDidLoad is very likely not the ideal place to register an observer. A common place to do this is the designated initializer, and removing it again in dealloc.
As a side note (and without seeing enough code for a very informed opinion), your use case ("remove all subviews") does not sound like notifications are a good approach. Have you considered using delegation?
It is possible that there is a double NSNotificationCenter registration.
I think you have declared another:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(removeAllSubViews:) name:#"getTheRequest" object:nil];
somewhere.. trying finding the other one..
And just a tip, when you register for NSNoticationCenter try removing first the observer like:
// removes the observer
[[NSNotificationCenter defaultCenter] removeObserver:YourObserver name:YourName object:YourObject];
followed by:
// register
[[NSNotificationCenter defaultCenter] addObserver:YourObserver selector:YourSelector name:YourName object:YourObject];
Just to remove the existing one, if any..

Remove notification observer from another view controller

Hi I am developing Iphone application in which am registering one notification observer for UIApplicationWillEnterForegroundNotification. Now I want to remove that one from another view controller. My code looks like
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(applicationBecomeActive)
name:UIApplicationWillEnterForegroundNotification
object:nil];
And I am creating one method for removing observer:
-(void) removeObserver
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
and I am calling this method from other view controller but its not working. I think I have to store observer. But I don't know how to do this. Need help. Thank you.
The second view controller needs a reference to the instance of the first view controller. Let's assume it is hold in a property:
#property (nonatomic, strong) FirstViewControler *firstViewController;
Then your code to remove the fist view controller as an observer would look like this:
- (void)removeObserver
{
[[NSNotificationCenter defaultCenter] removeObserver:self.firstViewController];
}
The missing part is: You have to set the property somewhere. Where to do that depends on your code.

How to tell a viewcontroller to update its UI from another class

I am trying to understand how updating of a viewController that is currently visible works.
I have ViewControllerA and ClassA. I want to tell ViewControllerA to reloadData on the tableview from ClassA. What is the best way to go about doing this?
I have found this question and answer but I dont think this will work in my situation or I am not understanding it correctly.
The easiest way without knowing your setup would be to use NSNotificationCenter. Here is what you could do:
In ViewControllerA add in hooks for NSNotificationCenter:
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
//Register for notification setting the observer to your table and the UITableViewMethod reloadData. So when this NSNotification is received, it tells your UITableView to reloadData
[[NSNotificationCenter defaultCenter] addObserver:self.table selector:#selector(reloadData) name:#"ViewControllerAReloadData" object:nil];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
//Need to remove the listener so it doesn't get notifications when the view isn't visible or unloaded.
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
Then in ClassA when you want to tell ViewControllerA to reload data just post the NSNotification.
- (void)someMethod {
[[NSNotificationCenter defaultCenter] postNotificationName:#"ViewControllerAReloadData" object:nil];
}
Answers here about using NSNotificationCenter are good. Be aware of a few other approaches:
A common one is the delegate pattern (see here and here).
Another is that the view controller observes the model change using KVO. (see here and here).
Another good one, often overlooked, which can probably be used in your case is the "do almost nothing" pattern. Just reloadData on your table view when viewWillAppear.
Key value Coding , NSNotificationCentre and Delegates are preferred. But NSNotificationCentre is easiest in your case.
The UIViewController that contains UITableView must add observer like this :
Init :
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(methodToReloadTable:)
name:#"TABLE_RELOAD"
object:nil];
In delloc method :
[[NSNotificationCenter defaultCenter] removeObserver:self];
Post it from any XYZ class like on any UIButton action :
[[NSNotificationCenter defaultCenter]
postNotificationName:#"TABLE_RELOAD"
object:self];
Advantage of NSNotificationCentre is that they can add observers in multiple classes ..

NSNotificationCenter observer is not getting removed?

I have added NSNotificationCenter in viewDidLoad method and removed in viewDidUnload but it's not getting removed. I am following ARC. I have followed few answer but I didn't get luck. I dont have reputation for give comments so posting some thing looks like duplicate. Please don't -ve votes.
Sample code:
- (void)viewDidLoad
{
[[NSNotificationCenter defaultCenter ] addObserver:self.containerView
selector:#selector(loadInitialScreen)
name:CLEARSCREEN_DEPOSIT
object:NULL];
}
- (void)viewDidUnload
{
[[NSNotificationCenter defaultCenter] removeObserver:self.containerView
name:CLEARSCREEN_DEPOSIT
object:nil];
}
You should remove the observer either in -viewWillDisappear:, -viewDidDisappear: or in the -dealloc method, depending on your needs. The reason is -viewDidUnload in iOS6+ is never called anymore and before iOS6 it's called when a memory warning is received.
Try to use viewDidDisappear instead viewDidUnload :
-(void)viewDidDisappear:(BOOL)animated
{
[[NSNotificationCenter defaultCenter] removeObserver:self.containerView
name:CLEARSCREEN_DEPOSIT object:nil];
[super viewDidDisappear:animated];
}
viewDidUnload is called (for < iOS 6.0), when a memory warning is received to the application/view controller.
It will not be called for removal of the view, for that dealloc is called. But as you are using ARC, you cannot implement dealloc method.
The best bet is to remove the observer in the method loadInitialScreen, if it has to be called only once.
If your notification can be posted multiple times, it's better to remove the observer in viewDidDisappear, but then add observer for the notification in ViewWillAppear

Resources