"sending 'const NSString *' to parameter of type 'NSString *' discards qualifiers" warning

Objective CNsstringWarningsConstants

Objective C Problem Overview


I have Constants NSString, that I want to call like:

[newString isEqualToString:CONSTANT_STRING];

Any wrong code here?

I got this warning:

> sending 'const NSString *' to parameter of type 'NSString *' discards qualifiers

How should these be declared?

Objective C Solutions


Solution 1 - Objective C

You should declare your constant string as follows:

NSString * const kSomeConstantString = @""; // constant pointer

instead of:

const NSString * kSomeConstantString = @""; // pointer to constant
// equivalent to
NSString const * kSomeConstantString = @"";

The former is a constant pointer to an NSString object, while the latter is a pointer to a constant NSString object.

Using a NSString * const prevents you from reassigning kSomeConstantString to point to a different NSString object.

The method isEqualToString: expects an argument of type NSString *. If you pass a pointer to a constant string (const NSString *), you are passing something different than it expects.

Besides, NSString objects are already immutable, so making them const NSString is meaningless.

Solution 2 - Objective C

just to put all on one place which found on various post on stackoverflow and works for me , #define is bad because you cannot benefit from variable types, basically the compiler replaces all occurrence when compiles (import Constants.h whenever you need) :

//  Constants.h
#import <Foundation/Foundation.h>

@interface Constants : NSObject

extern NSString *APP_STATE_LOGGED_IN;
extern NSString *APP_STATE_LOGGED_OUT;
@end

// Constants.m
#import <Foundation/Foundation.h>
#import "Constants.h"

@implementation Constants

NSString *APP_STATE_LOGGED_IN  = @"APP_STATE_LOGGED_IN";
NSString *APP_STATE_LOGGED_OUT = @"APP_STATE_LOGGED_OUT";
@end

Solution 3 - Objective C

spare few minutes to read this. A goodread on pointers hell on constants and vice-versa.

http://c-faq.com/decl/spiral.anderson.html

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser4951View Question on Stackoverflow
Solution 1 - Objective CalbertamgView Answer on Stackoverflow
Solution 2 - Objective Cfreezing_View Answer on Stackoverflow
Solution 3 - Objective Cuser3693546View Answer on Stackoverflow