Re: Is @"constantstring" pointer equal to @"constantstring" a guarantee?
Re: Is @"constantstring" pointer equal to @"constantstring" a guarantee?
- Subject: Re: Is @"constantstring" pointer equal to @"constantstring" a guarantee?
- From: glenn andreas <email@hidden>
- Date: Thu, 27 Mar 2008 21:52:15 -0500
On Mar 27, 2008, at 9:41 PM, Kyle Sluder wrote:
On Thu, Mar 27, 2008 at 9:16 PM, Jens Alfke <email@hidden>
wrote:
The linker coalesces multiple identical string constants into a
single
value in the data segment. However, you can still end up with
multiple
copies if your code was linked in separate pieces and then joined
together. Prior to Xcode 3.0 that used to happen when using
ZeroLink —
in fact, once or twice I've had my code crash when run with ZeroLink
because I'd inadvertently used pointer comparison instead of
isEqualToString: somewhere. Xcode 3.0 doesn't have ZeroLink anymore,
but the details of how your program gets linked together are not
something you should be relying on.
But it still makes sense to me that when I'm providing NSString
constants to be used as they are in the case of an NSError's userInfo
dictionary, for example, that pointer comparison is still valid. Of
course I wouldn't do it for places where I expect arbitrarily-provided
strings to be passed to my method, but I typically make my string
constants opaque.
Is this just in general a Bad Idea(TM)?
Bad Idea.
Consider that, at some point, you move your code into a framework that
you can reuse in multiple projects. While the linker can coalesce
constant strings within a single binary, it obviously doesn't go
across multiple binaries, so suddenly code that worked fine no longer
works (and you spend days tracking it down).
You could do what Coca does and declare your keys as variables:
extern NSString *NSFontAttributeName;
In this case, if you always used NSFontAttributeName (and never
@"NSFontAttributeName") you should be OK, because all places are
basically referring to the same variable value. This, of course,
assumes that the variable is _always_ used.
Of course, I'd be paranoid and just use isEqualToString: since that
has the fewest assumptions and is the safest (and the infinitesimal
performance penalty is completely overwhelmed by the time not spent
tracking down bugs by using "==").
Glenn Andreas email@hidden
<http://www.gandreas.com/> wicked fun!
quadrium | prime : build, mutate, evolve, animate : the next
generation of fractal art
_______________________________________________
Cocoa-dev mailing list (email@hidden)
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 email@hidden