Search code examples
objective-cconstantscllocation

What does the const specifier do, before a pointer to object?


If I have a C-string like this:

const char* str= "hello";

I know well that I can't change any character of the string because the pointer is const.
But if I have this:

- (CLLocationDistance)distanceFromLocation:(const CLLocation *)location

I can still mutate the object state using it's methods.
If the pointer is to a NSMutableString, I'm still able to mutate it.
Then what does the const stand for?


Solution

  • In that method declaration, location is a pointer to a constant CLLocation. But when you send a message to the location object, the const-ness is not preserved; the method that handles the message sees self as a non-const object. (Note that this is different than C++, which supports const member functions where this is a pointer to a constant object.)

    So the const in that declaration is not particularly useful. Perhaps it was written by someone used to the C++ way of doing things.

    When you do see const attached to an object pointer in Objective-C, it is usually like this:

    extern NSString * const SomeConstantString;
    

    This declares SomeConstantString as a constant pointer to some non-constant object (in this case, an NSString). The pointer itself is constant, so your program can't change SomeConstantString to point to some other NSString object.