成员变量与属性是不同的,先看如下示例代码:
User.h文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#import <Foundation/Foundation.h> @interface User : NSObject{ // 成员变量 NSString *name; NSInteger age;//typedef long NSInteger; } // 属性 @property(nonatomic,copy)NSString* address; @property(nonatomic,assign)CGFloat height; - (void)obtainInfo; @end |
User.m文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#import "User.h" @implementation User{ NSString *info; } @synthesize address = _address; //@synthesize height; - (void)obtainInfo{ NSLog(@"name = %@",self->name); NSLog(@"age = %ld",(long)age); NSLog(@"address = %@",self.address); NSLog(@"height = %f",self.height); NSLog(@"info = %@",info); } @end |
其中,定义成员变量格式(放在大括号中)为:
1 2 3 |
@interface User:Object{ .... } |
或者:
1 2 3 |
@impletation User{ ... } |
而属性则使用@property(和@synthesize)
定义的。
Xcode推荐的书写成员变量的形式是在变量名前添加下划线_
,例如:_name
。成员变量只能通过->
;符号来访问。
对于属性,使用@property
定义后,系统会自动生成setter
和getter
方法。
可以这样说,一个属性对应着一个成员变量;如果属性只使用@property声明,而没使用@synthesize的话,系统会自动的给你声明一个_开头的实例变量。如果又使用@synthesize的话,则相当于声明了一个实例变量,如果@synthesize address = _address;
,变量名为_address
;如果@synthesize address ;
,变量名为address
。
在类的内部该如何访问成员变量和属性呢?
如果,成员变量可以直接通过变量名访问,或者self->...
来访问;对于属性,如果没有定义@property
,则必须要用self.
属性名来访问。本质上,属性和成员变量处于一致的状态。