Women in Technology

Hear us Roar



Article:
  Strings in Cocoa: Part I
Subject:   Comparing @"..." type NSStrings
Date:   2001-07-06 15:30:29
From:   halliday
Incidentally, due to the uniqueness properties imposed by NSString upon NSString constants (@"..." type NSStrings), the example code:


NSString *string1 = @"A String";
NSString *string2 = @"A String";


BOOL result = string1 == string2;


evaluates to "yes" rather than "no". The compiler recognizes the second NSString to be the same as one it has already seen and simply reuses it. Since these NSStrings are immutable, there is no danger in doing so.


In fact, there are aspects of Cocoa that strongly rely upon this behavior.

Full Threads Oldest First

Showing messages 1 through 3 of 3.

  • Michael Beam photo Comparing @"..." type NSStrings
    2001-07-06 17:02:13  Michael Beam | O'Reilly Author [View]

    Is that right? Wow, i didn't realize that. Thanks for pointing that out. I guess it makes perfect sense. By the way, what are some of the features of Cocoa that rely on this fact as you mentioned?

    Mike
    • Comparing @"..." type NSStrings
      2001-07-07 01:18:41  halliday [View]

      Additionally, unless I'm misremembering, SELectors are implemented as unique @"..." type NSString constants as well.
    • Comparing @"..." type NSStrings
      2001-07-07 00:47:41  halliday [View]

      As the NSString documentation indicates (in it's Objective-C version): "The compiler makes such object constants unique on a per-module basis".

      Some of the features that rely upon this behavior are Pasteboard Types (they are really @"..." type NSStrings), various Attribute Keys, Exceptions, and Notifications (to name a few). Of course, this is an implementation detail, and is always subject to change.