首页 > 代码库 > 点语法
点语法
凡是符合系统默认setter、getter书写格式的方法都可以使?用点语 法。
#import "Student.h"
@implementation Student
- (void)setAge:(int)newAge {
age = newAge;
}
- (int)age {
return age;
}
@end
#import <Foundation/Foundation.h>
#import "Student.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
Student *stu = [[Student alloc] init];
// 设置age的值
stu.age = 10; // 等价于[stu setAge:10];
// 取出age的值
int age = stu.age; // 等价于int age = [stu age];
NSLog(@"age is %i", age);
[stu release];
}
return 0;
}
注意:在设置age的值时,将原来的[stu setAge:10]替换成stu.age = 10,两个式子完全等价,这也就是说,stu.age并不是直接访问stu对象的变量age,而是编译器遇到stu.age的时候,会自动将代码展开为[stu setAge:10]。直接访问应是stu->age,而非stu.age。
stu.age = 10 [stu age]的转换过程类似。
总结:OC点语法的本质是方法调用,不是直接访问成员变量。
验证方法:在get与set方法中设置NSLog输出语句。
点语法与self的陷阱:
1 - (void)setAge:(int)newAge {
2 self.age = newAge;
3 }
2 self.age = newAge;
3 }
错误:会造成死循环。
self.age相当于[self setAge:newAge];
自身调用自身。。。。。
点语法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。