我在閱讀這個guide時,有一個關於object-c中的手動內存管理的問題。object-c中的手動內存管理
有關問題更加清晰,我將代碼粘貼搞糊塗瞭如下:
// CarStore.m
- (void)setInventory:(NSMutableArray *)newInventory {
if (_inventory == newInventory) {
return;
}
NSMutableArray *oldValue = _inventory;
_inventory = [newInventory retain];
[oldValue release];
}
我覺得上面的代碼做了重複操作:
// CarStore.m
- (void)setInventory:(NSMutableArray *)newInventory {
// if we can ensure '_inventory' is different with 'newInventory'
if (_inventory == newInventory) {
return;
}
// we can release '_inventory' firstly and safely
[_inventory release];
_inventory = [newInventory retain];
}
也
// CarStore.m
- (void)setInventory:(NSMutableArray *)newInventory {
// if we don't check the equal between '_inventory' and 'newInventory' firstly
// then we need temp '_inventory', since '_inventory' and 'newInventory' maybe the same object
NSMutableArray *oldValue = _inventory;
_inventory = [newInventory retain];
[oldValue release];
}
我不確定在我的思想中是否有一些錯誤,所以請給我一個手。