今天讲Objective-C在类的继承情况下的初始化顺序。
Access Instance Variables Directly from Initializer Methods
Setter methods can have additional side-effects. They may trigger KVC notifications, or perform further tasks if you write your own custom methods.You should always access the instance variables directly from within an initialization method because at the time a property is set, the rest of the object may not yet be completely initialized. Even if you don’t provide custom accessor methods or know of any side effects from within your own class, a future subclass may very well override the behavior.
A typical init method looks like this:
- (id)init {
self = [super init];
if (self) {
// initialize instance variables here
}
return self;
}
An init method should assign self to the result of calling the superclass’s initialization method before doing its own initialization. A superclass may fail to initialize the object correctly and return nil so you should always check to make sure self is not nil before performing your own initialization.
By calling [super init] as the first line in the method, an object is initialized from its root class down through each subclass init implementation in order. Figure 3-1 shows the process for initializing an XYZShoutingPerson object.
Figure 3-1 The initialization process
As you saw in the previous chapter, an object is initialized either by calling init, or by calling a method that initializes the object with specific values.
In the case of the XYZPerson class, it would make sense to offer an initialization method that set the person’s initial first and last names:
- (id)initWithFirstName:(NSString *)aFirstName lastName:(NSString *)aLastName;
You’d implement the method like this:
- (id)initWithFirstName:(NSString *)aFirstName lastName:(NSString *)aLastName {
self = [super init];
if (self) {
_firstName = aFirstName;
_lastName = aLastName;
}
return self;
}