Objective-C : #define vs extern const

后端 未结 4 922
时光说笑
时光说笑 2021-02-19 22:37

I know this question has been asked before, but I can\'t seem to find information about it in Apple\'s documentation; maybe some of you guys did.

A lot of Objective-C co

相关标签:
4条回答
  • 2021-02-19 23:06

    Apple's recommendation is extern:

    Define constants for strings used for such purposes as notification names and dictionary keys. By using string constants, you are ensuring that the compiler verifies the proper value is specified (that is, it performs spell checking).

    Admittedly they are inconsistent about this sometimes.

    0 讨论(0)
  • 2021-02-19 23:20

    A #define defines a macro which is replaced before compilation starts where as extern *** *const merely modifies a variable so that the compiler will flag an error if you try to change it. There are some cases in that you would use a #define because you can't use a extern *** *const. In theory a extern *** *const will take up memory and requires a reference to memory but this is insignificant as it maybe optimized away from the compiler.

    extern *** *consts are a lot more compiler and debug friendlier then #defines this can be the deciding point when you decide which one to use.

    Some see that pre-processor directives like #define are frowned upon which would suggest you should be using extern *** *const over #define

    But whilst the pre-processor is frowned open some say it is more secure then a variable as it can't be changed at runtime whereas a variable can.

    Both have there advantages and disadvantages and I don't think (I can't find anything myself) that Apple recommends one over the other. My personal opinion is to use a mix of them both using a pre-processor directive #define over a extern *** *const where it would seem more beneficial, this is what I do.

    0 讨论(0)
  • 2021-02-19 23:20

    If you have some global constants, for example in a Constants.h which is imported in your prefix header and you're using a #define macro for these constants it's going to rebuild your whole project if you make any changes to these constants. In that case it is better to split your constants and use extern for strings, integers and everything else that you can use extern for.

    For example if you have extern NSString *const kServerURL; and you change your server address it's not going to rebuild your whole project but if you use define there, it's going to rebuild it. So the only purpose at least for me is for optimising the compile time.

    0 讨论(0)
  • 2021-02-19 23:23

    The trouble with using #defines over an extern, is that the compiler doesn't get to do any type checking. If you #define a string, there is nothing to stop you using it where you actually want, say, a number. If you use a static NSString instead, the compiler will emit a warning if you try to use it somewhere where it isn't expecting a string.

    0 讨论(0)
提交回复
热议问题