Ios#define and Static const

Source: Internet
Author: User
Tags naming convention uikit

Defining constants is best used with static const, without # define

Constants are often defined when writing code. For example, to write a UI view class, the view is displayed and then the animation is played, and then disappears. You may want to extract the time to play the animation as a constant. People who have mastered Objective-c and their C-language base may do so in this way:

#define ANIMATION_DURATION 0.3

The preprocessing instructions above replace the animation_duration string in the source code with 0.3. This may be the effect you want, but the defined constants do not have type information. The word "continuous" (duration) should appear to be time-related, but it is not explicitly stated in the code. In addition, the preprocessing process will replace all animation_duration encountered with 0.3, so that if this directive is declared in a header file, then all the code that introduced the header file, its animation_duration will be replaced.

To solve this problem, you should try to take advantage of some of the compiler's features. There is a better way to define constants than to use preprocessor directives. For example, the following line of code defines a constant of type nstimeinterval:

static const Nstimeinterval kanimationduration = 0.3;

Note that constants defined in this way contain type information, and the benefit is that the meaning of the constant is clearly described. The constant type is nstimeinterval, which helps to write the development documentation for it. If you want to define many constants, this way makes it easier for people who later read the code to understand their intentions.

Also pay attention to the constant name. The commonly used nomenclature is: if the constants are confined to a "compilation unit" (translation unit, which is the "implementation file", implementation "), then the letter K is preceded, and if the constant is visible outside the class, it is usually prefixed with the class name. The 19th article detailed the naming habit (naming convention).

It is important to define the position of the constant. We always like to declare pre-processing directives in the header file, which is really bad, especially if the constant names are likely to collide with each other. For example, animation_duration this constant name should not be used in the header file, because this name will appear in all other files that introduce this header file. In fact, the same constant as the static const definition should not appear in the header file. Because Objective-c does not have a "namespace" (namespace) concept, doing so is tantamount to declaring a global variable called kanimationduration. This name should be prefixed to indicate the class to which it belongs, for example, to Eocviewclassanimationduration. A clear set of naming schemes is explained in depth in article 19th of this book.

If you do not intend to expose a constant, you should define it in an implementation file that uses that constant. For example, to develop an iOS application that uses the Uikit framework, whose UIView subclass contains constants that represent the time of the animation playback, you can write:

// eocanimatedview.h   #import  <UIKit/UIKit.h>    @interface  EOCAnimatedView : UIView  -  (void) animate;  @ end   // eocanimatedview.m   #import   "EOCAnimatedView.h"     static const nstimeinterval kanimationduration = 0.3;   @ implementation eocanimatedview  -  (void) animate {           [uiviewanimatewithduration:kanimationduration animations:^ () {                  // Perform  animations                           }];  }        @end 

Variables must be declared with both static and Const. If you attempt to modify a variable declared by the const modifier, the compiler will error. In this case, we want this: because the animation plays at a fixed value, it should not be modified. The static modifier means that the variable is visible only in the compilation unit that defines the variable. Each time the compiler receives a compilation unit, it outputs a copy of the object file. In the context of objective-c, the term "compilation unit" usually refers to the implementation file of each class (with the suffix name of. m). Therefore, the kanimationduration variable declared in the example code above is scoped to only the target file generated by EOCANIMATEDVIEW.M. If the variable is declared without static, the compiler creates an "external symbol" (external symbol) for it. At this point the compiler throws an error message if a variable with the same name is also declared in another compilation unit:

Duplicate symbol _kanimationduration IN:EOCANIMATEDVIEW.O EOCOTHERVIEW.O

In fact, if a variable is declared as static and const, the compiler will not create a symbol at all, but will replace all encountered variables with constant values, just like the # define preprocessing directives. Remember, however, that constants defined in this way have type information.

Sometimes it is necessary to expose a constant externally. For example, you might want to call Nsnotificationcenter in your class code to notify others. Use an object to distribute notifications so that other objects that want to receive notifications are registered with the object so that this functionality can be achieved. When you distribute a notification, you need to use a string to represent the name of the notification, and the name can be declared as an externally visible constant variable (constant variable). In this case, the registrant does not need to know the actual string value, just register the notification you want to receive with a constant variable.

Such constants need to be placed in the global symbol table so that they can be used outside the compilation unit that defines the constant. Therefore, it is defined differently than the static const shown in the previous example. This should be defined as:

In the header file extern nsstring *const eocstringconstant; In the implementation file NSString *const eocstringconstant = @ "VALUE";

This constant is "declared" in the header file and "defined" in the implementation file. Note the Const modifier's position in the constant type. Constant definitions should be interpreted from right to left, so in this case, eocstringconstant is "a constant, and this constant is a pointer to the NSString object." This is consistent with demand: we don't want someone to change this pointer constant to point to another NSString object.

The compiler sees the extern keyword in the header file to understand how to handle the constant in the code that introduces the header file. This keyword is to tell the compiler that there will be a symbol called eocstringconstant in the global symbol table. That is, the compiler does not need to see its definition, which allows code to use this constant. Because it knows that this constant will definitely be found when it is linked to a binary file.

Such constants must be defined and can be defined only once. It is typically defined in an implementation file that is related to the header file that declares the constant. When a target file is generated by an implementation file, the compiler allocates storage space for the string in the data section. The linker will link this target file to other destination files to generate the final binary file. Wherever the eocstringconstant is used, the linker can parse the global symbol.

&NBSP;

 EOCLoginManager.h   #import  <Foundation/Foundation.h>  extern  nsstring *const eocloginmanagerdidloginnotification;    @interface   eocloginmanager : nsobject  -  (void) login;  @end    //  eocloginmanager.m   #import   "EOCLoginManager.h"    NSString *const  eocloginmanagerdidloginnotification =      @ " Eocloginmanagerdidloginnotification ";    @implementation  eocloginmanager   -   (void) login {      // perform login asynchronously,  then call  ' P_didlogin ' .  }   -  (void) p_didlogin {         [[nsnotificationcenter defaultcenter] postnotificationname :eocloginmanag    erdidloginnotification object:nil];  }   @end 

Note the name of the constant. To avoid name collisions, it is best to prefix the class names associated with them. This is generally done in the system framework. For example, Uikit declares a global constant that is used as the notification name in this way. There are constant names such as Uiapplicationdidenterbackgroundnotification and uiapplicationwillenterforegroundnotification.

The same is true for other types of constants. If you want to publish the animation of the Eocanimatedview class in the preceding precedent, then you can declare that:

EOCAnimatedView.h extern const Nstimeinterval eocanimatedviewanimationduration; eocanimatedview.m const Nstimeinterval eocanimatedviewanimationduration = 0.3;

Defining constants like this is better than using the # define preprocessing directives, because the compiler ensures that constant values do not change. Once defined in the EOCANIMATEDVIEW.M, it is ready to use anywhere. The constants defined by the preprocessing directives may inadvertently be modified, resulting in different values used by each part of the application.

In summary, do not use preprocessing directives to define constants, but rather to make sure that constants are correct by using a compiler, for example, you can declare constants in an implementation file with static const, or you can declare some global constants.

Points

Do not define constants with preprocessing directives. The defined constants do not contain type information, and the compiler simply performs a find-and-replace operation on this basis before compiling. Even if a constant value is redefined, the compiler does not produce a warning message, which results in inconsistent constant values in the application.

Use the static const in the implementation file to define constants that are visible only within the compilation unit (translation-unit-specific constant). Because such constants are not in the global symbol table, you do not need to prefix their names.

Use extern in the header file to declare global constants and define their values in the relevant implementation file. This constant is to appear in the global symbol table, so its name should be separated, usually prefixed with the class name associated with it.


Reference: http://book.51cto.com/art/201403/432132.htm


Ios#define and Static const

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.