> On 22 Sep 2016, at 02:05, Gabriel Zachmann <z...@tu-clausthal.de> wrote:
>> 
>>> how can the compiler know that '==' in this case is a NSString comparison?
>> 
>> It can’t because it isn't. What’s being compared are raw pointers. The 
>> string value is irrelevant.
> 
> Let me try to paraphrase, in order to check whether I am understanding 
> correctly.
> 
> Whenever I have two string literals @"XYZ" at different places in the same 
> compilation unit,
> and the XYZ are identical, then the compiler (or the Objective-C standard) 
> make sure that
> the pointers to those literals are identical?
> In other words, the compiler unifies the two occurrences of the two literals, 
> thus effectively storing only one literal?

 This is an optimization that Apple's compiler (and most compilers) currently 
apply for string constants, yes. However, they can only do that in the same 
executable. I.e. a framework or loadable plug-in bundle will get its own copy, 
as we can't know whether the executable loading it already has its own copy of 
that string or not. Also, of course, if you have an NSMutableString that ends 
up having the same content as an NSString, you get different addresses.

 If you want a more detailed answer, I blogged about this a while ago:

http://orangejuiceliberationfront.com/cocoa-string-comparisons-and-the-optimizer/

>> So, this technique is generally Not A Good Idea™.
> 
> If my understanding is correct, then I wholeheartedly agree.
> 
> That brings me to another question.  I've got this piece of code from an 
> example on MLMediaLibrary.
> 
> This is how I start the whole thing:
> 
>  [mediaLibrary_ addObserver: self
>                      forKeyPath: @"mediaSources"
>                         options: 0
>                         context: (__bridge void *) @"mediaLibraryLoaded"];
> 
> And this is the beginning of the corresponding KVO:
> 
> - (void) observeValueForKeyPath: (NSString *) keyPath   ofObject: (id) object
>                       change: (NSDictionary *) change context: (void *) 
> context
> {
>  MLMediaSource * mediaSource = [mediaLibrary_.mediaSources objectForKey: 
> MLMediaSourcePhotosIdentifier];
>  if ( context == (__bridge void *) @"mediaLibraryLoaded" )
>  {
> 
> So what would be the proper way to do it?  Should I just define my own string 
> constant?

Do

        void *kMediaLibraryLoadedKVOContext = &kMediaLibraryLoadedKVOContext;

for more details, see my other message in this thread.

-- 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