歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> iOS中正確處理dealloc方法

iOS中正確處理dealloc方法

日期:2017/3/1 10:25:26   编辑:Linux編程

當我們繼承類的時候,子類實例在構造的時候順序是先高用父類的構造方法,再調用子類的構造方法。在c/c++是如此,在objc中也是如此,在iOS開發中,我們會看到這樣的代碼:

  1. - (void)init
  2. {
  3. self = [super init];
  4. if (self)
  5. {
  6. //init
  7. }
  8. return self;
  9. }
看到沒,初始化的時候都是先調用父類的初始化方法,為什麼呢,因為父類更老,當然是先出生了。,同樣的情況可以在viewDidLoad中看到。

而銷毀的時候則是相反的順序,先銷毀子類裡分配的空間,再銷毀父類的。如:

  1. - (void)dealloc {
  2. [companion release];
  3. free(myBigBlockOfMemory);
  4. [super dealloc];
  5. }
為什麼會是這個順序呢?因為長江後浪推前浪,子類是繼承了父類的優點,發揮了自己長外, 敵人要想消滅對方,當然是先滅最強的,都說樹大招風,就是這個道理。在銷毀的時候如果不按這個順序,有時候可能會crash。如在子類中應用了:
  1. [outputStream setDelegate:self];
  2. [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

如果dealloc寫這成這樣就會在removeFromRunLoop的時候crash:

  1. - (void)dealloc {
  2. [super dealloc];
  3. if (outputStream) {
  4. [outputStream close];
  5. [outputStream removeFromRunLoop:[NSRunLoop currentRunLoop]
  6. forMode:NSDefaultRunLoopMode];
  7. [outputStream release];
  8. outputStream = nil;
  9. }
  10. delegate = nil;
  11. }
如果寫成這樣就ok了:
  1. - (void)dealloc {
  2. if (outputStream) {
  3. [outputStream close];
  4. [outputStream removeFromRunLoop:[NSRunLoop currentRunLoop]
  5. forMode:NSDefaultRunLoopMode];
  6. [outputStream release];
  7. outputStream = nil;
  8. }
  9. delegate = nil;
  10. [super dealloc]; // must be last!
  11. }

在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

Copyright © Linux教程網 All Rights Reserved