开发者

String constant ... best practise?

开发者 https://www.devze.com 2023-02-06 08:54 出处:网络
I\'m looking for a best practise of setting a code-wide used String constant Option 1 extern const NSString *cDownloadCompleteNotification;(.h file)

I'm looking for a best practise of setting a code-wide used String constant

Option 1

extern const NSString *cDownloadCompleteNotification; (.h file)

const NSString *cDownloadCompleteNotification = @"DownloadCompleteNotification开发者_如何学运维"; (.m file)

Option 2

define kNotificationDownloadComplete @"NotificationDownloadComplete" .... (common.h)

is there any benefit, one way or the other ? ... or just a case of personal preference ?


Personally, I go for the former though there's not much to choose between them. Memory usage is the same in both cases.

There's a few things to watch out for in a #define - e.g. what if you include the .h file twice.

If you use a define and then change the constant's value some of your files might be compiled with the old value and some with the new - you would find it very tricky to work out why your notification handlers were not being called! You'd have to clean before building just to make sure that you changed everything. This won't happen if you use an extern NSString.*

Hope that's helpful.

NB I wouldn't declare it as const - you get a compiler warning when passing it into the postNotificationName: methods on NSNotificationCenter :(

*XCode should be clever enough to mark files that include common.h as needing a rebuild if it changes but I've found it to have been wrong in the past.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号