> On Sep 21, 2016, at 4:44 PM, Gabriel Zachmann <z...@tu-clausthal.de> wrote:
> My question is: how can the compiler know that '==' in this case is a
> NSString comparison?
It doesn’t. In Obj-C, “==“ is always a pointer comparison even if it’s applied
to objects. It is NOT the same as -isEqual:.
This idiom with the `context` parameter of -observeValueForKeyPath: works
because the context is just an opaque pointer. You register the context when
you start observing, and the same exact pointer gets passed back to you when
you’re called. So you can use the context to identify which observation this
is, and since it’s just an opaque pointer value, you compare it using ‘==‘.
I’ve also seen people use C strings for this, i.e.
if (context == “mediaLibraryLoaded”) …
or just integers cast to void*:
if (context = (void*)1) …
The only danger when using string constants (NSString or char*) is that it’s
only safe to do this if all the code is being linked into the same binary. The
linker ensures that all references to “foo” refer to the same string constant
in memory. (Same with @“foo”.) If you have some code in the app and some other
code in a plugin library, though, they will almost certainly have different
pointer values for “foo” or @“foo”.
Cocoa-dev mailing list (Cocoafirstname.lastname@example.org)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to arch...@mail-archive.com