Re: Newbie question: constants
Re: Newbie question: constants
- Subject: Re: Newbie question: constants
- From: Wade Tregaskis <email@hidden>
- Date: Fri, 19 Nov 2004 16:02:39 +1100
Its a gcc thing, not an XCode thing. When gcc compiles a source file
to an object ( .o) file,
all duplicate references to a constant data value are removed (i.e.,
the data section of the
object file holds only one instance of @"myString", regardless of how
many times @"myString"
occured in the post-processed compilation unit. I do not know if the
linker removes duplicate
data constants. Anyone?
It's an XCode thing in so far as I'm not sure if it explicitly asks the
linker to remove duplicates... I have a feeling it doesn't, or at least
didn't in earlier versions.
With non-atomic types such as NSString's, you can't so easily use
defines, although it is possible in some cases - e.g. CFSTR("xxx")
will
return the constant NSString @"xxx", so you can #define myString
CFSTR("zzz"), I think.
#define MY_STRING @"FRED"
... works just fine.
There is some argument for using CFSTR instead, although I can't
remember exactly what... I suspect CFSTR is specially worked to resolve
to a single instance after linking when used in defines, whereas your
example above is not (but duplicates may be removed anyway).
NSString* const kMyString = @"some string";
works just fine in these cases. It's worth your while to learn how
'const'
works. Where it is positioned in a declaration is important. I'm
afraid i'm
lousy at explaining how it works. Anyone?
This only stops you changing the value kMyString points to - it doesn't
make the string itself constant. For immutable objects, that's not so
much an issue - for mutable ones, it is. Of course, as I alluded the
bigger problem with such a scenario is that your design is very poor
(or outright wrong).
Wade Tregaskis (AIM, Yahoo & Skype: wadetregaskis, ICQ: 40056898, MSN &
email: email@hidden, Jabber:
email@hidden)
-- Sed quis custodiet ipsos custodes?
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden