黑马程序员技术交流社区
标题: @property和@synthesize问题,求解 [打印本页]
作者: ★Joean_Zhou 时间: 2014-6-14 16:44
标题: @property和@synthesize问题,求解
//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
而不是我上面所解的呢???
作者: liulinjie 时间: 2014-6-14 17:20
不知道你有没有看到后面的视频: 如果不使用@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.
作者: chain 时间: 2014-6-14 18:28
我的csdn博客里面有一篇这道题的详细总结,http://blog.csdn.net/chainliu/article/details/29551849,你可以看看,期待与你交流
作者: ★Joean_Zhou 时间: 2014-6-15 21:59
谢谢你,偶看懂了。。。
作者: ★Joean_Zhou 时间: 2014-6-15 22:15
好的,谢谢你哦
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) |
黑马程序员IT技术论坛 X3.2 |