小谈 @synthesize 与 @dynamic


通常我们会这样做:

在Test.h中:

@interface Test : NSObject{
    NSString *_name;
}
@property(nonatomic,retain) NSString *name;
@end


在Test.m中:

@implementation Test
@synthesize name = _name;
@end

解析:使用@synthesize之后,编译器会自动帮我们生成setter和getter方法。






另一种情况:

在Test.m中:

@implementation Test

@dynamic name;

- (void)setName:(NSString *)newName
{
    if (_name != newName) {
        [newName retain];
        [_name release];
        _name = newName;
    }
}

- (NSString *)name
{
    return _name;
}

@end

解析:使用@dynamic,作用是告诉编译器我们自己定义setter和getter方法。 






概括:

当然写了@synthesize,我们也可以自己再定义一次setter和getter方法,这时我们自定义的就会覆盖编译器帮我们生成的方法。如果既不写@synthesize又不写@dynamic是可以的,这种情况就默认要我们自己定义setter和getter方法。但是写上是一种良好的编程习惯,好处是:如果太多属性的时候,我们只要一看这些指示符(@synthesize@dynamic),就知道每个属性是如何实现的。


如果我们写了@dynamic,但是没有自定义setter和getter方法,没有出现警告,可以编译,但是执行到setter或getter方法的时候会出错。






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值