我总是看到人们争论是否在-init
方法中使用属性的设置器。我的问题是如何在子类中为继承的属性创建默认值。假设我们有一个名为的类NSLawyer
——一个我无法更改的框架类——它的接口如下所示:
@interface NSLawyer : NSObject {
@private
NSUInteger _numberOfClients;
}
@property (nonatomic, assign) NSUInteger numberOfClients;
@end
一个看起来像这样的实现:
@implementation NSLawyer
- (instancetype)init
{
self = [super init];
if (self) {
_numberOfClients = 0;
}
return self;
}
@end
现在假设我想扩展NSLawyer
. 我的子类将被调用SeniorPartner
。而且由于高级合伙人应该有很多客户,所以在SeniorPartner
初始化时,我不希望实例以0
; 我希望它有10
。这是SeniorPartner.m:
@implementation SeniorPartner
- (instancetype)init
{
self = [super init];
if (self) {
// Attempting to set the ivar directly will result in the compiler saying,
// "Instance variable _numberOfClients is private."
// _numberOfClients = 10; <- Can't do this.
// Thus, the only way to set it is with the mutator:
self.numberOfClients = 10;
// Or: [self setNumberOfClients:10];
}
return self;
}
@end
那么,Objective-C 新手要做什么呢?好吧,我的意思是,我只能做一件事,那就是设置属性。除非我错过了什么。有什么想法、建议、提示或技巧吗?