A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© jiangenhao 中级黑马   /  2014-5-9 12:52  /  1384 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 jiangenhao 于 2014-5-9 19:15 编辑
  1. 1.@property和@synthesize
  2. #import <Foundation/Foundation.h>
  3. @interface Person : NSObject
  4. {
  5.     int _age;
  6.     int age;

  7.     int _height;
  8.     int height;

  9.     int _weight;
  10.     int weight;

  11.     int _money;
  12.     int money;
  13. }

  14. @property int age;
  15. @property int height;
  16. @property int weight;
  17. @property int money;

  18. - (void)test;
  19. @end

  20. @implementation Person
  21. @synthesize height = _height;
  22. @synthesize weight;

  23. - (void)setMoney:(int)money
  24. {
  25.     self->money = money;
  26. }

  27. - (int)height
  28. {
  29.     return 180;
  30. }

  31. - (int)age
  32. {
  33.     return age;
  34. }

  35. - (void)test
  36. {
  37.     NSLog(@"age=%d, _age=%d, self.age=%d", age, _age, self.age);
  38.     NSLog(@"height=%d, _height=%d, self.height=%d", height, _height, self.height);
  39.     NSLog(@"weight=%d, _weight=%d, self.weight=%d", weight, _weight, self.weight);
  40.     NSLog(@"money=%d, _money=%d, self.money=%d", money, _money, self.money);
  41. }
  42. @end

  43. int main()
  44. {
  45.     Person *p = [Person new];
  46.     p.age = 10;
  47.     p.weight = 50;
  48.     p.height = 160;
  49.     p.money = 2000;
  50.     [p test];
  51.     return 0;
  52. }

复制代码


请问self.age输出结果为什么为0

评分

参与人数 1技术分 +1 收起 理由
jing迪 + 1

查看全部评分

2 个回复

倒序浏览
楼主你的getAge方法是对_age复制;而getter返回的时age的值,你创建了一个p对象,调用点语法:
p.age = 10; 它相当于: [p setAge:10]; 而你的setAge方法是由 @property int age  生成;这句话默认会生产对:_age的setter;所以你的p.age = 10; 这个10 赋给了_age; 你有用self.age(也就是P.age)调用了getter,而getter你是自己写得,并且返回的时age,age的默认值是0;不知道楼主明白了吗;其实弄清楚者个问题,你只留两个成员变量:age, _age 其他的先注释了,不然会影响你的判断;

评分

参与人数 1技术分 +1 收起 理由
jing迪 + 1

查看全部评分

回复 使用道具 举报
讲得太好了 明白了 谢谢
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马