I have multiple instances of NSWindowController, who is registering for a notification to listen whenever edit happens.
Now when I edit something from one instance of windowcontroller, the notification gets posted and all the instances of that NSWindowcontroller listen to that notification,but I want only the instance which has updated its details to listen.
How can I achieve that?
As mentioned in the documentation for [NSNotificationCenter addObserver:selector:name:object:] method for parameter object:
The object whose notifications the observer wants to receive; that is,
only notifications sent by this sender are delivered to the observer.
If you pass nil, the notification center doesn’t use a notification’s
sender to decide whether to deliver it to the observer.
So just pass self as object.
E.G.
Registering for notifications:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(someSelector:)
name:#"SomeNotification"
object:self]; // <- SELF!!
Posting notification:
[[NSNotificationCenter defaultCenter] postNotificationName:#"SomeNotification"
object:self //<- SELF!!
userInfo:nil];
Related
Given this code in the viewDidLoad:
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:#selector(keyboardWillShow:) name:
UIKeyboardWillShowNotification object:nil];
[nc addObserver:self selector:#selector(keyboardWillHide:) name:
UIKeyboardWillHideNotification object:nil];
I'm asking myself if I need to delete the observers when I unload the view (or something similar).
It looks a bit like this question, but that question does not discuss if dealloc is deprecated since the use of ARC (edit: see comments in accepted answer).
But since ios updates all the time and I have no clue if you still would need to call dealloc and I've never seen a piece of code how to do this (delete the observers that is), some help would be appreciated :)
Yes, you do. Override dealloc in your view controller like so:
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
In general, you should remove an observer from a notification center when the observer is no longer needed -- either you don't need it to continue observing, or the object itself is being deallocated. You don't need to remove an object observing UIKeyboardWillHideNotification simply because the keyboard is going away, but you do need to remove it if you're getting rid of the object itself.
Consider what would happen if you didn't remove the observer before it was deallocated: if the notification it was watching for ever occurred, the notification center would try to send a message to that object. That would cause either a crash or some behavior that you don't expect, since the pointer the notification center used to send the message no longer points to the object that's supposed to observe the notification.
It is always good to have your notification observer's unregistered while they are not required.
Since your observer deals with Keyboard which is a visual element, have it unregistered, i.e. removed from observer on viewDidDisappear and have it re-register in viewWillAppear (something which i follow.).
This is required coz, in case you are pushing a new view controller over the one you are using, the observer will still be registered and can cause erroneous behaviour, and sometimes, if your view controller get deallocated, the notification will still have the observer registered and can lead to crash. Coz notification centre defaultCenter is a singleton instance for process and will be there for its lifetime.
Post iOS 6.0 you can call it in viewDidUnload. But iOS 6.0 that is deprecated.
I am working on an Iphone Application (ios5 + storyboard + arc).
I have 2 ViewControllers A and B.
In A I have a button. when pressed I am submitting a request asynchronously to the server (using AFNetworking) and I will go to View Controller B by using performSegueWithIdentifier (push not modal).
When the request finishes it executes a request successful Block that will save data to the database. (The block is in ViewController A since the request is sent from there)
Is there a way I can notify ViewController B that the request has finished and execute a method in B?
What I'm looking for is that when the request finishes and enters the Success Block I run a method in view controller B which is the loaded view.
I hope I was clear.
Thanks
For posting a notification use the below code:
[[NSNotificationCenter defaultCenter] postNotificationName:#"Midhun" object:nil];
In the viewDidLoad of the notification listening class add observer like:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(performTask:) name:#"Midhun" object:nil];
performTask: is the method which will be called when the notification is observed.
Please refer NSNotification Class Reference
First options is to store reference to view controller B somewhere (as example in application delegate) and use it to run a method.
The second one is to send notification via [NSNotificationCenter defaultCenter], so controller B set a listener to a notification somewhere (viewDidLoad can be a good place):
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(finished:) name:#"requestfinishes" object:nil];
and controlle A sends it:
[[NSNotificationCenter defaultCenter] postNotificationName:#"requestfinishes" object:nil userInfo:nil];
Note that if you send a notification from a different thread, listener will be executed on the same thread.
Im working on an ios app, ios 5+ , using xcode and objective c. Ok currently messing with nsnotifications and i just need some clarifications as im a wee bit confused.
Lets say i have a view controller that i add an observer to like so
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(showContent:) name:kTPSShowContentNotification object:self];
where the object is set to self. I took this to mean that it is only looking from that notification if sent from that object. am i wrong on that?
elsewhere in code I am positing a notification like so
[[NSNotificationCenter defaultCenter] postNotificationName:kTPSShowContentNotification object:currentVC];
where currentVC is the view controller that has the observer set up initially.
I thought this is all that was needed to catch that notification as the post is telling the notification center to send it from that view controller. but it fails to catch it and im unsure as to why. If when adding the observer i set the object as nil then it catches it but so does all the other viewcontrollers (if any ) that have observers for that notification too. Is there any way around this ? am i approaching this completely wrong?
To receive notification only from theObjectSendingNotification object you should write:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(showContent:) name:kTPSShowContentNotification object:theObjectSendingNotification];
and the object sending notification should send it in this way
[[NSNotificationCenter defaultCenter] postNotificationName:kTPSShowContentNotification object:self];
If I'm getting this right, you want to post and get a notification from the same controller. So you can do something like this:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(showContent:) name:kTPSShowContentNotification object:self];
[[NSNotificationCenter defaultCenter] postNotificationName:kTPSShowContentNotification object:self];
But it should work indeed if your currentVC ivar is pointing to the very same controller. The fact that you say it doesn't work makes me believe that it is not pointing to the same instance of your controller.
I have a observer problem with NSNotificationCenter in my app.
My AppDelegate class has 2 service class to get data by url which called ExhibitionService & NewsService.
This 2 service class uses one Queueloader class in itself.
When I wrote 2 observer to listen service load operations in my appdelegate class, it returns error and crashes.
APP DELEGATE CLASS
ExhibitionLoaderService *exhibitionService = [[ExhibitionLoaderService alloc] init];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(exhitibionServiceComplete :) name:**CserviceComplete** object:nil];
[exhibitionService load];
NewsLoaderService *newsService = [[NewsLoaderService alloc] init];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(newsServiceComplete :) name:**CserviceComplete** object:nil];
[newsService load];
ExhibitionLoaderService.m & NewsLoaderService has the same method
-(void)load
{
Queueloader *que = [[Queueloader alloc] initWithPath:CExhibitionURLPath isVerbose:NO];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(didQueComplete:) name:CdidQueueloaderComplete object:nil];
[que startOperation];
[que release];
}
ERROR I GOT
[[NSNotificationCenter defaultCenter] postNotificationName:**CdidQueueloaderComplete** object:results];
2 service class has CdidQueueloaderComplete... Problem is about observers but how? what?
PS. Program received signal EXC_BAD_ACCESS.
Thanks.
There's no problem with having multiple observers of the same notification. The problem you describe sounds a lot like it's related to the lifetime of your observers.
If you deallocate an object that's still registered to listen to notifications, the NSNotificationCenter doesn't know about that. If a notification comes in in the future, the center will forward it to the object it thinks is still listening (but that has gone away), and you get a crash.
The solution to this problem is to ensure that your object is removed as an observer before it is destroyed. There are two ways to do this:
often you'll know when an object should start or stop listening to notifications, and you can make sure you remove it as an observer when it should stop (for example, perhaps view controllers should start listening for model updates when their views appear and stop listening when their views disappear)
other times, an object can look after its own notification lifecycle: perhaps you can start listening in an initialiser and stop listening in -dealloc.
Whatever way you do it, you need to balance adding observers and removing observers so that when an object goes away it's no longer registered with the notification center.
I have a class with 2 NSNotifications implemented
//Set up notifications
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(getData)
name:#"Answer Submitted"
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(reloadTable)
name:#"Comment Submitted"
object:nil];
I would just like to check if it is ok to set 2 observers in a single class? Also when I remove observer, I am only removing one observer in dealloc method. Is that an issue?
It is perfectly fine to have more than one observer in a single class. You should always unregister the observer once you're done with it.
More details on the Observer pattern in Objective-C can be found here.