2013-08-26 74 views
3

我現在面臨小問題,如何釋放內存聲明的對象在iPhone

我宣佈在.h文件中的數組,並在viewDodLoad方法分配它。在dealloc方法中,我檢查數組是否不等於nil,然後是array=nil。但它在iOS 5.1.1中崩潰。我無法理解這次事故的原因。

我的代碼,

@interface SampleApp : UIViewController 
    { 
     NSMutableArray *objArray; 
    } 
    @end 

    @implementation SampleApp 

    - (void)viewDidLoad 
    { 
     [super viewDidLoad]; 
     objArray=[[NSMutableArray alloc]init]; 
    } 
    -(void)dealloc 
    { 
     [super dealloc]; 
     if (objArray!=nil) 
    { 
     [objArray removeAllObjects]; 
     [objArray release];objArray=nil; 
    } 
    } 

回答

3

dealloc方法的末尾添加[super dealloc];,而不是在開頭。 Apple推薦使用documentation for dealloc method

當不使用ARC時,您的dealloc實現必須調用超類的實現作爲它的最後一條指令。

修改如下代碼,

-(void)dealloc 
    { 
     if (objArray!=nil) 
    { 
     [objArray removeAllObjects]; 
     [objArray release];objArray=nil; 
    } 
     [super dealloc]; 
    } 

另外,你需要不叫[objArray removeAllObjects]當你釋放整個數組。當數組被釋放時,它將在內部對所有包含的對象調用release

希望有幫助!

1

[super dealloc]方法必須在此方法結束時調用。因爲您不能再訪問超類的變量,因爲它們在您調用[super dealloc]時被釋放。在最後一行中調用超類總是安全的。

-(void)dealloc 
    { 

// ----------- your stuff ------------ 

     [super dealloc]; 

    } 
+0

謝謝你@ Dharmir Choudary – Ravi

+0

歡迎@Ravan –

0

隨着手動內存管理,你-dealloc方法如下所示:

-(void)dealloc 
{ 
    [objArray release]; // objArray *may* be nil, and this is 
          // sufficient to release all elements as well. 

    // call super at the end 
    [super dealloc]; 
} 

此外,你在你的方法-viewDidLoad有一個潛在的內存泄漏。如果你不喜歡它的例子:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    objArray=[[NSMutableArray alloc]init]; 
} 

可以分配objArray一個新的指針,即使objArray已經持有有效的對象。新的指針值將覆蓋舊的,因此你不能再釋放舊的。

一種方法是檢查objArray是否爲nil,然後分配一個新值之前,釋放它:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    if (objArray) { 
     [objArray release], objArray = nil; 
    } 
    objArray = [[NSMutableArray alloc]init]; 
} 

更好的方法卻是採用「懶初始化屬性」:

第一,爲你的數組定義一個「內部屬性」(除非你希望數組可公開訪問)。在您的.m文件中:

// In your implementation file define a private property in a class extension: 
@interface SampleApp() 
@property (nonatomic) NSMutableArray* objArray;  
@end 


@implementation SampleApp 

@synthesize objArray = _objArray; // this will create the setter 

-(void)dealloc 
{ 
    [_objArray release]; 
    [super dealloc]; 
} 

// Lazy init property: (this is the getter) 
- (NSMutableArray*) objArray { 
    if (_objArray == nil) { 
     _objArray = [[NSMutableArray alloc] init]; 
    } 
    return _objArray; 
} 

- (void) viewDidLoad { 
    [super viewDidLoad]; 

    // When needing the array, simply *and always* access it 
    // through the property "self.objArray": 
    NSUInteger count = [self.objArray count]; 
} 

... 

屬性的惰性初始化非常方便。基本上,如果它們已經初始化或不初始化,那麼當你使用屬性訪問器時它們就不會再擔心了。