當我們繼承類的時候,子類實例在構造的時候順序是先高用父類的構造方法,再調用子類的構造方法。在c/c++是如此,在objc中也是如此,在iOS開發中,我們會看到這樣的代碼:
- - (void)init
- {
- self = [super init];
- if (self)
- {
- //init
- }
-
- return self;
- }
看到沒,初始化的時候都是先調用父類的初始化方法,為什麼呢,因為父類更老,當然是先出生了。,同樣的情況可以在viewDidLoad中看到。
而銷毀的時候則是相反的順序,先銷毀子類裡分配的空間,再銷毀父類的。如:
- - (void)dealloc {
- [companion release];
- free(myBigBlockOfMemory);
- [super dealloc];
- }
為什麼會是這個順序呢?因為長江後浪推前浪,子類是繼承了父類的優點,發揮了自己長外, 敵人要想消滅對方,當然是先滅最強的,都說樹大招風,就是這個道理。在銷毀的時候如果不按這個順序,有時候可能會crash。如在子類中應用了:
- [outputStream setDelegate:self];
- [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
如果dealloc寫這成這樣就會在removeFromRunLoop的時候crash:
- - (void)dealloc {
- [super dealloc];
- if (outputStream) {
- [outputStream close];
- [outputStream removeFromRunLoop:[NSRunLoop currentRunLoop]
- forMode:NSDefaultRunLoopMode];
- [outputStream release];
- outputStream = nil;
- }
- delegate = nil;
- }
如果寫成這樣就ok了:
- - (void)dealloc {
- if (outputStream) {
- [outputStream close];
- [outputStream removeFromRunLoop:[NSRunLoop currentRunLoop]
- forMode:NSDefaultRunLoopMode];
- [outputStream release];
- outputStream = nil;
- }
- delegate = nil;
- [super dealloc]; // must be last!
- }
在xCode version:4.2.1及以前版本中開發iOS的時候,如果將super dealloc寫在子類dealloc中前面的時候是不會出錯的,但在xCode version4.3.2中,它會有自動檢測super dealloc的功能,如果寫在前面,則會crash.
蘋果官網也推薦這樣寫,請參看:
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html#//apple_ref/occ/instm/NSObject/dealloc 中的特別注意事項中
Special Considerations
When garbage collection is enabled, the garbage collector sends finalize to the receiver instead of dealloc, and this method is a no-op.
If you are using manual reference counting, subclasses must implement their own versions of dealloc to allow the release of any additional memory consumed by the object—such as dynamically allocated storage for data or object instance variables owned by the deallocated object. After performing the class-specific deallocation, the subclass method should incorporate superclass versions of dealloc through a message to super