@synthesize
2019-02-19 本文已影响0人
RobinZhao
Xcode4时,@property只能生成getter、setter方法的声明;
从Xcode5开始,@property 可以自动生成_propertyName成员变量和getter、setter方法的声明和实现。默认情况下,getter、setter方法作用于_propertyName变量。
但是,当同时重写getter和setter两个方法的时候,实现了完全的自定义实现,无法对应到默认的变量_propertyName,_propertyName就无效了,需要手动定义一个变量或者使用@synthesize指定一个变量来绑定到属性上,通过@synthesize改变了属性、getter、setter对应的变量,这点很有用处,比如可以在子类修改父类中readonly属性的值,可以修改协议中属性值。
PersionProtocol.h
#import <Foundation/Foundation.h>
@protocol PersionProtocol <NSObject>
@property (nonatomic, strong) NSString *weight;
@end
Persion.h (遵守PersionProtocol协议)
#import <Foundation/Foundation.h>
#import "PersionProtocol.h"
@interface Persion : NSObject <PersionProtocol>
@property (nonatomic, strong, readonly) NSString *gender;
@property (nonatomic, assign) NSInteger age;
@end
Persion.m
@implementation Persion
@synthesize weight;
@synthesize age = nianLing;
- (instancetype)init {
self = [super init];
if (self) {
self.weight = @"100Kg"; // protocol中的属性 实现@synthesize weight;
}
return self;
}
// 同时修改getter和setter方法时要实现@synthesize name = na 添加一个别名; 或者手动添加一个别称
- (void)setAge:(NSInteger)age {
nianLing = age;
}
- (NSInteger)age {
if (nianLing > 18) {
nianLing = 18; // 永远18岁
}
return nianLing;
}
@end
Mary.h (继承Persion类)
#import "Persion.h"
@interface Mary : Persion
@end
Mary.m
@implementation Mary
// 子类中要访问父类readonly属性时
@synthesize gender = xingbie;
- (instancetype)init {
self = [super init];
if (self) {
self.age = 29;
xingbie = @"man";
self.weight = @"50Kg";
}
return self;
}
@end
- (void)viewDidLoad {
[super viewDidLoad];
Mary *mary = [[Mary alloc] init];
// 结果:man--18---50Kg
NSLog(@"%@--%ld---%@",mary.gender,mary.age,mary.weight);
}