Unlike Java, objc has static constants. For example:
Pubstatic final radias = 180;
My current practice is to use C's preprocessing # define. For example, in the header file:
# Define min_velocity 10
# Define loop_count 100
@ Interface animationview: uiview <uigesturerecognizerdelegate> {
Use in the Code:
If (data. panlocation. x <min_x ){
Data. panlocation. x = min_x;
}
These predefined constants are replaced by strings defined in define during compiler compilation.
----------------------------------------------------------
Best practices for using constants in the objc Project
Previously, using constants in the objc project, using the C preprocessing # define to set constants. For example, you can create a header file and import it in the required class file to use constants.
But this is not the best practice. This may be the best method. First, in the header file named constants. h:
# Import <Foundation/Foundation. h>
Extern nsstring * const kiniturl;
@ Interface constants: nsobject {
}
@ End
The extern C keyword is used here to indicate that the variable has been declared and is only referenced. The const keyword indicates that the variable is a constant and cannot be modified.
In the objc convention, constants are also case-and-case mixed hump naming rules. The first letter is lowercase, and the first letter is K.
Then, in the constants. M file:
# Import "constants. H"
Nsstring * const kiniturl = @"Http://marshal.easymorse.com ";
@ Implementation Constants
@ End
Assign a value to the constant kiniturl.
How to Use constants? You only need to introduce the constants header file in the required M file. The following is an example:
# Import "basicdemosviewcontroller. H"
# Import "constants. H"
@ Implementation basicdemosviewcontroller
// Implement loadview to create a view hierarchy programmatically, without using a nib.
-(Void) loadview {
Nslog (@ "load view: % @", kiniturl );
}
In this way, you can compare the pointer of a constant, which is beyond the reach of # define. That is:
[Myurl isw.tostring: kiniturl];
------------------------------------------------
Internal constant of the objc File
Constants in the best practice of using constants in the objc project are constants that can be used globally. If you only use it inside the file and do not want access from other places, you need:
# Import "basicdemosviewcontroller. H"
# Import "constants. H"
Nsstring * const kmyurl = @ "http://marshal.easymorse.com ";
@ Implementation basicdemosviewcontroller
// Implement loadview to create a view hierarchy programmatically, without using a nib.
-(Void) loadview {
Nslog (@ "load view: % @, % @", kiniturl, kmyurl );
}