OC语言--@porperty、@synthesize

一、@property和@synthesize

在类的声明中我们会写一大堆的成员变量和成员变量对应的get、set方法,在类的实现中我们还需要将类的set、get方法进行实现,但是无论是类的声明还是类的实现,很多代码都是类似的,所有成员变量的set方法都是类似的,所有get方法又是相似的,所以我们在写代码的时候发现很多工作都是没有技术含量的,代码很多,但是完成的功能都是一样的。所以苹果公司为了减少程序员的这些没有技术含量的工作,让程序员将精力放在程序的功能上,苹果公司提供了property和@synthesize。
@property:翻译:所有者
@synthesize:翻译:合成、综合

二、@property和@synthesize的应用示例:
//一般的类的声明:
@interface Person : NSObject
{
    int _age;    
    int _weight;                
    int _height;    
}
- (void)setAge:(int)age;
- (int)age;

- (void)setWeight:(int)weight;
- (int)weight;

- (void)setHeight:(int)height;
- (int)height;
@end

//应用@property的声明:(等同于上面的声明)
@interface Person : NSObject
@property int age;
@property int weight;
@property int height;
@end
//一般的类的实现:
@implementation Person
- (void)setAge:(int)age
{
    _age = age;
}
- (int)age
{
    return age;
}

- (void)setWeight:(int)weight
{
    _weight = weight;
}
- (int)weight
{
    return weight;
}

- (void)setHeight:(int)height
{
    _height = height;
}
- (int)height
{
    return _height;
}
@end

//应用@synthesize的类的实现(等同于上面的实现):
@implementation Person
@synthesize age = _age;
@synthesize weight = _weight;
@synthesize height = _height;
@end

三、@property和@synthsize解析

1、 @property和@synthsize的这种作用是编译器的特性,当编译器遇到@property和@synthsize时就会自动将代码进行转化:

2、 @property的作用:可以自动生成某个成员变量的getter和setter的声明,由左边自动转化为右边代码:
       @property int age;    <==>   - (void)setAge:(int)age;
                             - (int)age;             
3、 @synthesize的作用:可以自动实现getter和setter;
       @synthesize age = _age;    <==>   - (void)setAge:(int)age
                                {
                                    _age = age;
                                }
                                - (int)age
                                {
                                    return _age;
                                }
            @synthesize char * name;  <==>  - (void)setName:(char *)name  //编译器会自动生成一个@private的name变量
                                {
                                    name = name;
                                }
                                - (int)name
                                {
                                    return name;
                                }
                             
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值