Re: Creation of constants
Re: Creation of constants
- Subject: Re: Creation of constants
- From: "Alastair J.Houghton" <email@hidden>
- Date: Fri, 31 Oct 2003 12:00:09 +0000
On Friday, October 31, 2003, at 11:44 am, j o a r wrote:
On 2003-10-31, at 11.45, Alastair J.Houghton wrote:
For string constants, you can declare an external global variable e.g.
extern const char *MY_C_STRING;
extern NSString *MY_NS_STRING;
Why did you use the const type qualifier for the (char *) and not the
(NSString *)?
It means something slightly different (before anyone gets confused,
this *isn't* a language issue... "const" in ObjC always means exactly
what it meant in C, which is almost but not quite the same thing it
means in C++).
Basically, const char * means a pointer to a character (or array of
characters) that you can't change... i.e. the const applies to the
*string*.
Whereas const NSString * would mean a pointer to a constant NSString
object (i.e. an object whose member variables cannot be changed), which
is quite different. NSString already makes the guarantee about the
string's contents being immutable, but in order to function as an
Objective C class, it needs to be able to manipulate its member
variables.
When I do this:
const NSString *kMyKey = @"MyKey";
...instead of this:
const id kMyKey = @"MyKey";
...I get this warning:
MyClass.m:666: warning: passing arg 1 of `isEqualToString:'
discards qualifiers from pointer target type
...for this piece of code:
if ([key isEqualToString: kMyKey])
Why is that, and how would you fix it - by using id, or by removing
const? I notice that if I omit the const type qualifier, I no longer
get the warning - but then I also loose the benefits of using the type
qualifier.
You probably don't want the const. The reason you don't get the
warning for the "id" is that a const id is equivalent to a constant
pointer, *not* a pointer to a constant object. i.e. the equivalent
with NSString would be
NSString * const kMyKey = @"MyKey";
and not
const NSString *kMyKey = @"MyKey";
(Incidentally, you can use the extra const to prevent assignments to
your "constants"; for example,
extern const char * const MY_C_STRING;
extern NSString * const MY_NS_STRING;
the only problem being that if you're working with people that don't
know their C very well, you'll constantly be bombarded with "why did
you put the const there?" type questions and you might even find that
someone "reformats" them by moving the const to the wrong place :-))
Section 6.2.5 "Types" of the C99 standard talks about this; in
particular, see Example 1.
Kind regards,
Alastair.
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.