隨着手動內存管理,你-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];
}
...
屬性的惰性初始化非常方便。基本上,如果它們已經初始化或不初始化,那麼當你使用屬性訪問器時它們就不會再擔心了。
謝謝你@ Dharmir Choudary – Ravi
歡迎@Ravan –