黑马程序员技术交流社区
标题:
self.的问题
[打印本页]
作者:
jiangenhao
时间:
2014-5-9 12:52
标题:
self.的问题
本帖最后由 jiangenhao 于 2014-5-9 19:15 编辑
1.@property和@synthesize
#import <Foundation/Foundation.h>
@interface Person : NSObject
{
int _age;
int age;
int _height;
int height;
int _weight;
int weight;
int _money;
int money;
}
@property int age;
@property int height;
@property int weight;
@property int money;
- (void)test;
@end
@implementation Person
@synthesize height = _height;
@synthesize weight;
- (void)setMoney:(int)money
{
self->money = money;
}
- (int)height
{
return 180;
}
- (int)age
{
return age;
}
- (void)test
{
NSLog(@"age=%d, _age=%d, self.age=%d", age, _age, self.age);
NSLog(@"height=%d, _height=%d, self.height=%d", height, _height, self.height);
NSLog(@"weight=%d, _weight=%d, self.weight=%d", weight, _weight, self.weight);
NSLog(@"money=%d, _money=%d, self.money=%d", money, _money, self.money);
}
@end
int main()
{
Person *p = [Person new];
p.age = 10;
p.weight = 50;
p.height = 160;
p.money = 2000;
[p test];
return 0;
}
复制代码
请问self.age输出结果为什么为0
作者:
godlike
时间:
2014-5-9 13:47
楼主你的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 其他的先注释了,不然会影响你的判断;
作者:
jiangenhao
时间:
2014-5-9 19:13
讲得太好了 明白了 谢谢
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2