IOS variable definition and usage
Let's take an example. Create a new ViewController class. Xcode automatically generates two files for us: ViewController. h and ViewController. m.
1. member variables
@ Interface ViewController: UIViewController {// we call myTest1 a member variable BOOL myTest1;} @ end
@ Implementation ViewController-(void) viewDidLoad {myTest1 = NO; // usage of self. myTest1 or [self myTest1] is not supported} @ end
The member variable does not use @ synthesize. This attribute is a private attribute and does not change the reference count when being assigned a value,
The default member variable is protected. Generally, non-subclass objects cannot be accessed.
2. member variables of class Extension
@interface ViewController : UIViewController@end
// Class extensions are all placed in. above @ implementation in the m file, otherwise the @ interface ViewController () {// member variable BOOL myTest2;} @ end @ implementation ViewController-(void) of the class extension will be held) viewDidLoad {myTest2 = YES; // usage is the same as 1} @ end
In fact, this expression is the same as 1. The difference is that the private information of. H files is better hidden.
3. attribute variables
@ Interface ViewController: UIViewController // attribute variable. If @ synthesize is not used, only the public attribute @ property (nonatomic, copy) NSString * str1; @ end
@ Implementation ViewController @ synthesize str1 = _ str1; // synthesize getter and setter, put it in @ implementation-(void) viewDidLoad {// usage that does not exist, directly reporting str1 = @ abc; // correct usage 1 _ str1 = @ abc; // attribute name prefix _ indicates public attribute, when @ property is declared, the system automatically adds // correct usage 2 NSString * astr = [self str1]; NSLog (@ % @, astr); // correct usage 3 self. str1 = @ 123;} @ end
4. member variables of class Extension
@interface ViewController : UIViewController@end
@ Interface ViewController () // attribute variable of class extension @ property (nonatomic, copy) NSString * str1; @ end @ implementation ViewController @ synthesize str1 = _ str1; // meaningless-(void) viewDidLoad {// incorrect usage str1 = @ 345; // correct usage self. str1 = @ 123; // correct usage _ str1 = @ 678; // correct usage NSString * aStr = [self str1];} @ end
No @ synthesize actually works the same way, because str1 is not published by. h. The @ property defined in class extension is more convenient to use self. str1 and [self str1.