Remove an NSNotification observer that may not exist - objective-c

I can not seem to find a definitive answer on this topic.
Is it okay to remove an observer that may not exist?
Example Code:
-(void)commonInit{
[[NSNotificationCenter defaultCenter]removeObserver:self];
[[NSNotificationCenter defaultCenter]addObserver:self
selector:#selector(userDidChangePrecision:)
name:kUser_Changed_Precision
object:nil];
}
-(void)dealloc{
[[NSNotificationCenter defaultCenter]removeObserver:self];
[super dealloc];
}
This would prevent more than one observer being initialized for the object in the case where the object may be reinitialized during run time.

Snippet from the Apple docs:
- (void)removeObserver:(id)notificationObserver
Parameters
*notificationObserver*
The observer to remove. Must not be nil.
- (void)removeObserver:(id)notificationObserver name:(NSString *)notificationName object:(id)notificationSender
Parameters
*notificationObserver*
Observer to remove from the dispatch table. Specify an observer to remove only entries for this observer. Must not be nil, or message will have no effect.
In both cases, the warning that observer not be nil is overstated; the effect, in both cases, is that this message has no effect. Neither compiler nor runtime errors, no zombies, &c.
Likewise, specifying an observer that is not observing also has no effect.
Not a definitive answer, but based on observations and investigations of playing with trial-and-error code such as:
[[NSNotificationCenter defaultCenter] removeObserver:nil];
[[NSNotificationCenter defaultCenter] removeObserver:[UIView new]];

I can't find definitive documentation on if it's allowed to remove non-existent observers but I think the NSNotificationCenter documentation can be read in this way. It says that removeObserver:name:object: removes matching observers. I'm just assuming that this includes no matching observers.
But here's another reason why your approach might be harmful: When your commonInit method is being called other code (sub- or superclasses' init) might already have registered to notifications. When subclassing a UIViewController that's even likely (for memory warnings).
So I'd say you should never unconditionally unregister from notification center, except in dealloc.

Related

Why can't I observe NSApplicationXYZNotification with addObserverForName?

I'm trying to make an Objective-C iOS library work for macOS applications. Removing UIKit-based notifications is the only real task here. When trying to replace—for example—UIApplicationDidEnterBackgroundNotification with NSApplicationDidResignActiveNotification, I run into the odd error of the latter variable being called an undeclared identifier.
[self.observers addObject: [[NSNotificationCenter defaultCenter] addObserverForName:NSApplicationDidResignActiveNotification object:nil queue:nil usingBlock:^(NSNotification* note) {
// stop operations
}]];
The same error does not arise when I use the alternate method:
[[NSNotificationCenter defaultCenter] addObserver:[???] selector:[some selector] name:NSApplicationDidResignActiveNotification object:nil];
The problem with this method though is that I have to have an observer beforehand—like self—as opposed to receiving one that I can add to the self.observers array.
I've read a smattering of docs, questions, and guides—including the NSApplication doc and the NSHipster guide—but I can't seem to figure out my misunderstanding, though I believe it is something fundamental about NSNotificationCenter and how it works.
Silly solution, though aided by #Willeke's comment that they weren't seeing an error with the same code snippet—the library needed Cocoa.h in place of the iOS imports.

NSNotificationCenter removeObserver: in dealloc and thread-safety

I'm using ARC and I'm calling [[NSNotificationCenter defaultCenter] removeObserver:someObserver]; in observer's dealloc.
From NSNotificationCenter Class Reference
Be sure to invoke this method (or removeObserver:name:object:) before
notificationObserver or any object specified in
addObserver:selector:name:object: is deallocated.
NSNotificationCenter does not retain the observer.
Q1: Is NSNotificationCenter thread-safe?
In case, the observer is being deallocated(and removing observer from the notification center) and another thread post a notification at the same time.
I encounter random crash and I suspect this is the case.
Q2: Is this situation possible?
Q3: Does it lead to EXC_BAD_ACCESS?
Q4: Then, is it safe to call [[NSNotificationCenter defaultCenter] removeObserver:someObserver]; in observer's dealloc?
Q5: If it is not safe, where should I call removeObserver:?
I just stumbled into this problem myself: I had one notification just in the process of being sent (which always happens in the main thread) while the object was in the process of being deallocated from a background thread. I fixed it by simply performing removeObserver in the main thread and waiting:
- (void)removeNotificationCenterObserver
{
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter removeObserver:self];
}
- (void)dealloc
{
[self performSelectorOnMainThread:#selector(removeNotificationCenterObserver) withObject:self waitUntilDone:YES];
}
This waits until the current run loop cycle ends and executes this message at the beginning of the next run loop cycle. This ensures that any functions that are still running will finish.
Yes, NSNotificationCenter doesn't retain observer, but it still has a pointer to it in it's dispatch table.
Q1: Quoting Apple docs
Regular notification centers deliver notifications on the thread in which the notification was posted. Distributed notification centers deliver notifications on the main thread. At times, you may require notifications to be delivered on a particular thread that is determined by you instead of the notification center. For example, if an object running in a background thread is listening for notifications from the user interface, such as a window closing, you would like to receive the notifications in the background thread instead of the main thread. In these cases, you must capture the notifications as they are delivered on the default thread and redirect them to the appropriate thread.
Q2,3: Yes.
Q4,5: AFAIK it's safe unless you stumble into circular reference.
I usually add/remove in -viewWillAppear:/-viewWillDisappear: for UIViewControllers and -init/dealloc for other classes.
I've wondered the same thing, and I can't find it documented. Here's what I think is going on.
removeObserver: is not thread safe in the way that you want it to be.
Think about the following situation. The last reference to the observer is released while executing code on thread A. Thread A will call the observer's dealloc method. At the same time, the observed object executes a [NSNotificcationCenter postNotificationName:object:] from thread B. This leads to an unavoidable race condition. That is, a notification will be in flight while your object is within its dealloc method.
- (void)init {
...
[[NSNotificcationCenter defaultCenter] addObserver:self
selector:#selector(callback:)
name:#"whatever"
object:nil];
...
}
- (void)dealloc {
// If the observed object posts the notification on thread B while
// thread A is here, there's a race! At best, thread B will be
// in callback: while thread A is here in dealloc. That's probably
// not what you expect. The worst case is that thread B won't make
// make it to callback: until after thread A completes the dealloc
// and the memory has been freed. Likely crash!
[[NSNotificationCenter defaultCenter] removeObserver:self];
// If the observed object does the post when thread A is here,
// you'll be fine since the observation has been removed.
}
This isn't a problem for main thread objects that are only observing other main thread objects since, by definition, you can't get into the thread A and B scenario I described.
For multi-threaded cases, the only way to guarantee you'll avoid the problem is to ensure that the observation stops before the observer's refcount hits 0. If someone else is responsible for the observer's lifetime (i.e. you have any sort of term or close method), it's easy. If not, I don't know of a solution.

Is dispatch_async(dispatch_get_main_queue(), ...) necessary in this case?

I came across this piece of code, and I can't quite figure out why the author did this. Take a look at this code:
someMethodStandardMethodUsingABlock:^() {
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:"notif" object:nil];
});
}];
I have a method with a completion block, and in this block a notification has to be posted. I don't quite understand why the dispatch_async on the main queue is necessary in this case. The block will already be run on the main thread, and even if it wasn't I don't think it would really matter would it? I would simply have written this:
someMethodStandardMethodUsingABlock:^() {
[[NSNotificationCenter defaultCenter] postNotificationName:"notif" object:nil];
}];
And it does work in my testing.
If you can help me shed some light on this, I'd really appreciate it!
Matt
These 2 sentences from the NSNotificationCenter Class Reference suggest a couple of possible reasons:
A notification center delivers notifications to observers
synchronously. In other words, the postNotification: methods do not
return until all observers have received and processed the
notification.
...
In a multithreaded application, notifications are always delivered in
the thread in which the notification was posted, which may not be the
same thread in which an observer registered itself.
So perhaps (a) the author doesn't want the code to block until all observers have processed the notification, and/or (b) he wants to ensure that the observer methods run on the main thread.
Sometimes you need to run methods that fire some execution asynchronously and return right away. E.g. some of the AppDelegate 'key' methods like applicationDidBecomeActive, or applicationDidEnterBackground, need to be executed and return quickly so the OS doesn't kill your app.
I don't know if that is the case of your question, but it is a possible explanation of the usage of dispatch_async.

Is it OK for a view to know about its controller?

I'd like my controller to subscribe to notifications from view. However, before doing that, I'd like to confirm if it is OK for a view to know the instance of its controller?
Let me offer you a more specific example of what I have in mind.
My controller creates the view and informs it that it is its controller
self.gameView = [[GameView alloc] initWithController:self];
Once done, it subscribes for notifications from this view
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(saySomething:)
name:#"SaySomethingClever" object:nil];
Meanwhile the view does its thing, but when the right time comes, it posts a notification
[[NSNotificationCenter defaultCenter] postNotificationName:
#"SaySomethingClever" object:gvc];
In order for it to do it, the view needs to know the recipient of the notification (gvc).
I'd like to use this opportunity and as you whether the following is ok:
When initWithController is called, the view
-(id) initWithController: (GameViewController* )g {
gvc = g;
return [self initWithFrame:CGRectMake(0, 0, 480, 300)];
}
where initWithFrame:CGRectMake is a private method that handles specific view stuff.
Everything works fine, however, i wonder whether this approach is morally acceptable
It's not strictly a problem if the view has a reference to its controller, but it looks like your real problem is a misunderstanding of the notification posting method.
The object argument isn't the receiver. Indeed, if it were -- if the poster of a notification had to know the object that was going to get the notification -- that would defeat the entire purpose of the notification. You could just call the appropriate method! The point of notifications is that the poster doesn't need to know the other objects which are listening.
The object argument is actually used by the receiver to distinguish which notifications it should care about. Most frequently, the argument is the poster itself:
[[NSNotificationCenter defaultCenter] postNotificationName:IDidSomethingInteresting
object:self];
but it can in fact be any object.
When registering for notifications, you can specify a particular instance whose notifications you're interested in. This is the object argument to addObserver:... The notification center will then only pass on those notifications whose name and object match what was specified.
Even if you pass nil for the object in addObserver:..., you can check the object of a received notification and only act if the poster was one that you are interested in.
For example, there might be several windows in you application, and you may be interested in knowing when one of them is resized, but you don't care what happens to the rest of them. You would pass just that window instance as the object for addObserver:...
To sum up, your view in this case doesn't need that reference to its controller in order to for the controller to receive notifications posted by the view.
See also: "Posting Notifications"
While the concept is OK, it's not needed in your case:
[[NSNotificationCenter defaultCenter] postNotificationName:#"SaySomethingClever"
object:self];
The object referenced by an NSNotification is usually the object which posts a notification. The whole notification idea is that posters don't need to know about observers.
I would focus on controllers calling other controllers (or ideally model methods).
Allow each view to work with it's main resource and allow the controller for that view to make additional calls.

Removing an Observer

In a NSManagedObject Sub Class I have the code …
- (void) awakeFromInsert {
[self addObserver:[NSApp delegate] forKeyPath:#"name" options:NSKeyValueObservingOptionNew context:nil];
}
Which adds my App Delegate as an Observer, what I want to do now is from inside my App Delegate, I want to remove itself as an Observer for my NSManagedObject Sub Class.
How would I do this?
Thanks.
I was thinking of adding this to my App Delegate
[JGManagedObject removeObserver:self forKeyPath:#"name"];
but unfortunately removeObserver:forKeyPath: is not a Class Method.
For something like this, it's probably best to rethink the design. The delegate, in this case, would have to have some specific knowledge of the managed object itself in order to do this -- and the delegate would have to have some idea about when in the lifecycle it should (or would want to) stop observing the object.
You have a few choices. Instead of doing this in awake from insert, you could have the delegate start observing it when it creates it and then stop observing it when it gives up ownership. If that is not feasible in your design, you could have the object remove its observer when it is deallocated. If this is a fire-and-forget (basically the delegate only cares once), you could remove the observer after the first change notification. Since, however, you created the observation within the creation lifecycle of this object, it is probably best to remove that observation at the destruction of the object:
- (void)dealloc
{
[self removeObserver:[NSApp delegate] forKeyPath:#"name"];
// other clean-up
[super dealloc];
}
You might also want to do this when the object awakes from fetch and from fault and release the observer when the object will become a fault.
Much the same way you added the observer in the first place, only with fewer options:
// Given some managed object "object"...
[object removeObserver:self forKeyPath:#"name"];
Note that we remove self as the observer, rather than the application delegate as given by [NSApp delegate], since the code will be running within the delegate itself.
How about sending your object the removeObserver:forKeyPath message just before you delete it from the ManagedObjectContext?
From iOS 11 and above, we have automatic registration of KVO. From the Foundation Release Notes for macOS 10.13 and iOS 11
Relaxed Key-Value Observing Unregistration Requirements
Prior to 10.13, KVO would throw an exception if any observers were still registered after an autonotifying object's -dealloc finished running.
Additionally, if all observers were removed, but some were removed
from another thread during dealloc, the exception would incorrectly
still be thrown. This requirement has been relaxed in 10.13, subject
to two conditions:
• The object must be using KVO autonotifying, rather than manually
calling -will and -didChangeValueForKey: (i.e. it should not return NO
from +automaticallyNotifiesObserversForKey:) • The object must not
override the (private) accessors for internal KVO state
If all of these are true, any remaining observers after -dealloc
returns will be cleaned up by KVO; this is also somewhat more
efficient than repeatedly calling -removeObserver methods.