1,oc中的点语法本质上还是对方法的调用,并不是像java中对成员变量的访问。
2,点语法是编译器特性,它会自动展开为对应的set和get方法。
3,点语法例子:
#import <Foundation/Foundation.h>
//类的声明
@interface Persion : NSObject{
int _age; //成员变量
}
//set和get方法
- (void)setAge:(int)age;
- (int)age;
@end
//类的实现
@implementation Persion
- (void)setAge:(int)age
{
_age = age;
}
- (int)age
{
return _age;
}
@end
main函数中
#import <Foundation/Foundation/h>
#import "Persion.h"
int main(int argc, const char * argc[])
{
//创建一个Persion类对象
Persion *per = [[Persion alloc] init];
per.age = 20; //系统会自动变为[per setAge:20];
int age = per.age; //相当于传统的get方法[per age];
NSLog(@"age is %i", age);
return 0;
}
4,注意self使用点语法的情况,当self和 . 有时候一起使用时可能会造成死循环
- (int)age
{
return self.age;
}