Alex Rivera | Logout

How to declare NSString constants for passing to NSNotificationCenter

Asked 2010-05-27T01:29:19.130
23

I've got the following in my .h file:

#ifndef _BALANCE_NOTIFICATION
#define _BALANCE NOTIFICATION
const NSString *BalanceUpdateNotification
#endif

and the following in my .m file:

const NSString *BalanceUpdateNotification = @"BalanceUpdateNotification";

I'm using this with the following codes:

[[NSNotificationCenter defaultCenter]
    addObserver:self
    selector:@selector(updateBalance:)
    name:BalanceUpdateNotification
    object:nil];

and

[[NSNotificatoinCenter defaultCenter]
    postNotificationName:BalanceUpdateNotification
    object:self userInfo:nil];

Which works, but it gives me a warning:

Passing argument 1 of 'postNotificationName:object:userInfo' discards qualifiers from pointer target type

So, I can cast it to (NSString *), but I'm wondering what the proper way to do this is.

Edit
Report

1 Answer

1

Typically, one does not make these variables constant. One would, on the other hand, declare them as externs in the header file. This is (a little bit) because when you say const NSString *string, you are telling the compiler that the memory pointed to by string will not change -- this is both not useful and not necessarily true, being that we have no control over how apple's classes manage state variables. (Although NSStrings declared at runtime are placed in the text segment, functionality could change across versions or something.) If you truly wanted to use const, which I still advise against, it should be NSString * const string, which will prevent the pointer from being altered to point to a different memory location (which it would not do otherwise);

answered 2010-05-27T01:38:14.613

Your Answer