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

© ★Joean_Zhou 中级黑马   /  2014-6-14 16:44  /  1519 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

//1.@property和@synthesize
#import <Foundation/Foundation.h>

//创建Person这个类
@interface Person : NSObject
{
    int _age;  //年龄
    int age;

    int _height;  //身高
    int height;

    int _weight;  //体重
    int weight;

    int _money;  //钱
    int money;
}

//各种getter和setter声明
@property int age;  
@property int height;
@property int weight;
@property int money;

//test的声明
- (void)test;
@end

@implementation Person
@synthesize height = _height;  //_height的getter和setter实现
@synthesize weight;  //weight的getter和setter实现

- (void)setMoney:(int)money //money的set方法
{
    self->money = money;
}

- (int)height    //height的get方法
{
    return 180;
}

- (int)age   //age的get方法
{
    return age;
}

- (void)test
{
    NSLog(@"age=%d, _age=%d, self.age=%d", age, _age, self.age);
    //age = 10,_age = 0,self.age = 10;
    NSLog(@"height=%d, _height=%d, self.height=%d", height, _height, self.height);
    //height = 0,_height = 160,self.height = 160
    NSLog(@"weight=%d, _weight=%d, self.weight=%d", weight, _weight, self.weight);
    //weight=50,_weight=0,self.wight=50
    NSLog(@"money=%d, _money=%d, self.money=%d", money, _money, self.money);
    //money=2000,_money=0,self.money=2000
}
@end

int main()
{
    Person *p = [Person new];
    p.age = 10;   //age = 10
    p.weight = 50;  //weight = 50
    p.height = 160;  // _height = 160
    p.money = 2000;  //money = 2000
    [p test];
    return 0;
}
输出为什么是 age=0, _age=10, self.age=0
height=0, _height=160, self.height=180
weight=50, _weight=0, self.weight=50
money=2000, _money=0, self.money=0
而不是我上面所解的呢???

评分

参与人数 1技术分 +1 收起 理由
傘が咲く + 1

查看全部评分

4 个回复

倒序浏览
不知道你有没有看到后面的视频:  如果不使用@synthesize, 只使用@property声明的属性, 自动生成的set和get方法都是设置 _属性名 的值.

1> age, _age, self.age
你写了 @property int age; 并实现了 -(int)age 方法, 所以编译器会生成 _age 的set方法:
- (void)setAge: (int)age {
    _age = age;           // 自动生成的setter方法设置的是 _age
}
p.age = 10; 调用了 setAge: 方法, 把 _age 的值设置为10. age 的值没有设置, 仍然为0.
打印 self.age 的值时, 调用的是 age 方法, 这个方法你实现了, 返回 age 的值, 所以打印为0.

2> self.height
打印self.height时, 调用height 方法, 你实现了这个方法并返回180, 所以打印的是180, 不是160.

3> self.money
打印 self.money时, 调用的是money的get方法. 使用 @property int money; 自动生成的get方法返回的是 _money 的值. 所以打印的是 _money 的值 0.


评分

参与人数 1技术分 +1 收起 理由
傘が咲く + 1

查看全部评分

回复 使用道具 举报
我的csdn博客里面有一篇这道题的详细总结,http://blog.csdn.net/chainliu/article/details/29551849,你可以看看,期待与你交流
回复 使用道具 举报
liulinjie 发表于 2014-6-14 17:20
不知道你有没有看到后面的视频:  如果不使用@synthesize, 只使用@property声明的属性, 自动生成的set和get ...

谢谢你,偶看懂了。。。
回复 使用道具 举报
chain 发表于 2014-6-14 18:28
我的csdn博客里面有一篇这道题的详细总结,http://blog.csdn.net/chainliu/article/details/29551849,你可 ...

好的,谢谢你哦
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马