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.
Typically you declare the variable as extern
in the header. The most idiomatic way seems to be like this:
#ifndef __HEADER_H__ #define __HEADER_H__ extern NSString * const BalanceUpdateNotification; #endif
#include "header.h" NSString * const BalanceUpdateNotification = @"BalanceUpdateNotification";
extern
tells the compiler that something of type NSString * const
by the name of BalanceUpdateNotification
exists somewhere. It could be in the source file that includes the header, but maybe not. It is not the compiler's job to ensure that it does exist, only that you are using it appropriately according to how you typed it. It is the linkers job to make sure that BalanceUpdateNotification
actually has been defined somewhere, and only once.
Putting the const
after the *
means you can't reassign BalanceUpdateNotification
to point to a different NSString
.
NSStrings
are immutable, so declaring a const NSString *
would be redundant; just use NSString *
.
If what you're trying to do is declare that the pointer itself can't change, that would be:
NSString * const BalanceUpdateNotification = @"BalanceUpdateNotification";
See also Constants in Objective-C
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With