ArticleDirectory
- [Obj-C note] "Self = [Super init]" explanation and hidden bugs
[Obj-C note] "Self = [Super init]" explanation and hidden bugs
The recommended init Method for objective-C is written as follows:
-(ID) Init {If (Self = [Super init]) {// Add attributes to the subclass for initialization} return self ;}
Several questions are involved here,
1. [Super init:
Object orientation: first, use the init method of the parent class to initialize the attributes of the parent class of the subclass instance.
2. Why should self be assigned a value of [Super init]:
In simple terms, it is to prevent the parent class's initialization method from dropping the space pointed by self and re-alloc a space. In this case, [Super init] may fail alloc, and then the statement in IF is no longer executed.
3. The essence of super as the message recipient:
Super is not a real pointer. The essence of [Super message] Is that self accepts the message of the parent class. Note that in [Super message], the message method displays self in the context of [Super message], that is, the subclass instance.
Hidden bugs:
Assume that there is a parent class aobj and a subclass bobj.
When the init method of aobj is as follows:
-(ID) Init {id tmp = self; self = [aobj alloc]; [TMP release]; // other staffs return self ;}
The init method of bobj is as follows:
-(ID) Init {If (Self = [Super init]) {// other staffs} return self ;}
At this time, the compilation is successful, but when the bobj instance uses the bobj extended attribute, a runtime error will occur. The cause of the error is that the aobj init method uses [aobj alloc] to obtain a space that is only suitable for storing the aobj instance. The init method of bobj thinks that this is a space suitable for storing bobj. A running error occurs when you try to read and write bobj's extended attributes.
Therefore, when the init method needs to re-alloc a space, the correct syntax is as follows:
-(ID) Init {id tmp = self; self = [[self class] alloc]; [TMP release]; // other staffs return self ;}
Note that [self class] will obtain the class instance corresponding to the instance to which self points. In this example, It is bobj. In this way, the init method of any subclass of aobj can ensure security.