Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare NSString constants for passing to NSNotificationCenter

Tags:

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.

like image 331
synic Avatar asked May 27 '10 01:05

synic


2 Answers

Typically you declare the variable as extern in the header. The most idiomatic way seems to be like this:

Header

#ifndef __HEADER_H__ #define __HEADER_H__  extern NSString * const BalanceUpdateNotification;  #endif 

Source

#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.

like image 148
dreamlax Avatar answered Sep 19 '22 18:09

dreamlax


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

like image 36
David Gelhar Avatar answered Sep 23 '22 18:09

David Gelhar