------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
点语法
/*
1. 点语法:
如果实例变量已经实现了get 和 set 方法,此时,我们使用对象名 + . + 实例变量名
替代之前的设置值和获取值的方式
设置值: 以前-->[对象 setXXX:值]; ---> 对象.实例变量名 = x;
获取值: 以前-->[对象 (get)方法名]; ---> 对象.实例变量名
2. 点语法的实质:
点语法,是编译器特性,当编译器遇到p.name的时候,会自动的根据程序的
上下文环境,自动转换成 set方法或者get方法
小规律:
如果 对象.实例变量名 右边有 = (被赋值),就是set
p.age = 10; ---> [p setAge:10];
如果 对象.实例变量名 右边没有 = (被赋值),就是get
p.age ----> [p age];
点语法的陷阱(造成无限循环):
1> 在set方法中 使用了 self.xxx = xxx;
-(void)setAge:(int)age{
//self.age -----> [self setAge:age];
//下面的写法会造成无限循环
// self.age = age;
_age = age;
}
2> 在get方法中 使用了 self.xxx
-(int)age{
//点语法替换: self.age ----> [self age];
// return self.age;
return _age;
}
*/
#import <Foundation/Foundation.h>
@interface Person : NSObject
{
int _age;
}
//age的set 和get 方法的声明
- (void)setAge:(int)age;
- (int)age;
@end
//实现
@implementation Person
- (void)setAge:(int)age
{
_age = age;
}
- (int)age
{
return _age;
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
// 创建一个person类的对象
Person *p = [Person new];
p.age = 10;
NSLog(@"年龄是%d",p.age);
}
return 0;
}