Use a constant as a path not working


Hi guys,
i just read this chapter and started with the next where we gonna create a text file. I wanted to combine both chapters and use a constant as my path value. Unfortunately my implementation does not work. Can someone give me hint what I’m doing wrong?

Here is my sample:

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
    @autoreleasepool {
        NSString const *path = @"/Users/foo/temp/cool.txt";
        NSMutableString *str = [[NSMutableString alloc]init ];
        for(int i=0; i<10; i++)
            [str appendString:@"Aaron is cool!\n"];
        [str writeToFile:path

            NSLog(@"done writing %@",path);
    return 0;

Here is the error:

Sending const NSString *__strong to parameter of type NSString * discards qualifiers

I used the implementation from the book. I thought I’m sending a NSString as a message to the method and not a const. What I’m doing wrong?




Oh I see this is only a warning and the code is running but still i would gladly now why i get this warning?!


Presumably because an NSString object cannot be modified in place, and thus the const declaration is unneeded, the method signature for writeToFile doesn’t include const for the first argument (your path variable).

Thus, when you call writeToFile with a pointer to a const value, the compiler recognizes that writeToFile makes no guarantees and warns you (I doubt what you saw was an error, more likely a warning).

I’d call this a bit of conceptual mismatch between C and Objective-C; some of the inevitable clash between two languages written in different eras for different purposes.


Thanks for the explanation. At this point it is true it makes no sense to use a const for a path but i wanted to try it. Fixing the error is no problem. What I was thinking is that the method writeToFile (or objective-c) should look what type is behind the const? Is it a string or an int or something else? Otherwise i have to decide in each method declaration if i want to accept a const or only a string/interger…?


I’m not sure I follow the question, but in general, there’s no harm in using const liberally when defining methods of your own except when you want to forward one of those arguments to a method outside your control.

I would assume Apple consistently fails to declare const on immutable object parameters, and that we should follow that lead. If you declare a method to take a const object and later add a call to an Apple library using that object, you are effectively breaking the promise that you made by using const, unless you clone the object before passing it along.