> On 22 Sep 2016, at 02:01, Graham Cox <graham....@bigpond.com> wrote:
> 
> 
>> On 22 Sep 2016, at 9:44 AM, Gabriel Zachmann <z...@tu-clausthal.de> wrote:
>> 
>> I have found on the net 
> 
> That isn’t always a recommendation ;)
> 
> 
>>  if ( context == (__bridge void *) @"mediaLibraryLoaded" )

Gabriel,

this is a pointer comparison, not a string comparison. If the addObserver call 
happens in another module (usually unlikely) or Apple changes how its compiler 
coalesces string constants, this will break.

> Don’t do this, even if it appears to work. You got lucky, or are taking 
> advantage of undocumented implementation details.
> 
> This should be: if([(NSString*)context 
> isEqualToString:@“mediaLibraryLoaded”])…
> 
> I expect the first thing -isEqualToString: does is a pointer comparison, so 
> it’s unlikely to be significantly less performant for the case of when the 
> pointers are literally identical.

No, Graham, don't do that!

There is no guarantee that the context is a valid object. It is just supposed 
to be a unique pointer value so your class can tell a KVO notification from 
notifications for other observers on the same object (e.g. if a subclass 
observes the same value as a base class).

The best (but a bit clever) way to declare your context is

        void* kMediaLibraryLoadedContext = &kMediaLibraryLoadedContext;

this may look invalid, but actually just reserves a bit of memory in your app's 
globals section that now has a unique address. As a convenience, it writes this 
address into itself. So instead of &kMediaLibraryLoadedContext you can just 
write kMediaLibraryLoadedContext.

Cheers,
-- Uli



_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

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:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to