本文共 1754 字,大约阅读时间需要 5 分钟。
以成员变量 NSString *companyName为例:
1. 纯手工定义以及点语法:AppDelegate.h@interface AppDelegate : UIResponder{ ASIDownloadCache *myCache; NSString *companyName; //NSString *_companyName; 变量签名添加下划线,纯粹是命名习惯,和OC语法无关}@property (strong, nonatomic) UIWindow *window;@property (nonatomic, retain) ICSDrawerController *drawer;@property (nonatomic, retain) rootBackViewController *rootVC;@property (nonatomic,retain) ASIDownloadCache *myCache;@end
@implementation AppDelegate......-(void) setCompanyName:(NSString*)str { companyName = str;}-(NSString*) companyName{ return companyName;}......-(void) func { //这里点语法赋值,是OC的语法之一,作用就是自动调用setter和getter函数,也可以通过@property 让编译器自动生成 self.companyName = @"Google Inc."; NSstring name = self.companyName; }@end
AppDelegate.h@interface AppDelegate : UIResponder{ ASIDownloadCache *myCache; //NSString *companyName; 注意,这里可以不显示定义成员变量}@property (strong, nonatomic) UIWindow *window;@property (nonatomic, retain) ICSDrawerController *drawer;@property (nonatomic, retain) rootBackViewController *rootVC;@property (nonatomic,retain) ASIDownloadCache *myCache;@end
@implementation AppDelegate......//不需要自己定义getter和setter方法,会自动生成......-(void) func { //注意这里语法编译不过,因为我们没有显示定义companyName成员变量 companyName = "Baidu Inc." //点语法调用,通过@property 让编译器自动生成的getter和setter self.companyName = @"Google Inc."; NSstring name = self.companyName; }@end
所以,这里有几个概念,自动动手run一下,就清楚了:
1. 点语法的作用:直接调用 对应的getter或setter方法 2. @property关键字的作用,自动生成getter和setter方法,供点语法调用。另外一对要注意,如果只用@property定义了成员变量,而没有在interface的大括号中定义,那么@property会自动给你定义这个成员变量的,只是这个由@property自动定义的成员变量,你是不能够直接访问的,只能通过点语法访问 3. 同上,在interface的大括号中定义成员变量的作用:如果定义了,就能够直接访问,否则只能通过点语法访问 4. 成员变量加下划线前缀:纯粹的习惯写法,和OC语法无关转载地址:http://fyqrj.baihongyu.com/