[英]Preventing to alloc the same array more than once
初學者的問題:我有一種將數據放入 MutableArray 的方法。 潛在地,這個方法可以被多次調用,我有點擔心它會泄漏 memory 因為我在每次調用它時分配數組:
indexContent = [[NSMutableArray alloc] init];
int numberOfEntries = [noteBookContent count]/3;
for (int k=0; k < numberOfEntries; k++) {
IndexItem *newItem = [[IndexItem alloc] init];
newItem.itemTitle = [noteBookContent objectAtIndex:(k*3)];
newItem.itemPage = k;
if (![[noteBookContent objectAtIndex:(k*3)] isEqualToString:@""]) {
[indexContent addObject:newItem];
}
[newItem release];
}
如果indexContent = [[NSMutableArray alloc] init];
實際會發生什么被調用不止一次? 如果它很糟糕,我該如何防止這種情況發生? 例如,我應該在 viewDidLoad 中調用它嗎? 但是,如果我嘗試進行“延遲加載”,即僅在我真的需要時才分配 indexContent,我將如何處理它? 有沒有辦法檢查它是否已經分配?
如果這一切都很明顯,我很抱歉,但我正在努力解決這個問題。 也許這是一個我還沒有完全掌握的基本概念。 謝謝!
編輯:
我有
@property (nonatomic, 保留) NSMutableArray *indexContent; 在我的 header
if (indexContent == nil) indexContent = [NSMutableArray new]; // i screwed up logic first time. derp.
確保在發布indexContent
時將其設置為 nil;
[indexContent release];
indexContent = nil;
(除非它是dealloc
方法,但在那里可能仍然是一個好主意)
請注意,這假設您要重用並可能進一步填充現有數組。 如果沒有,您可以removeAllObjects
或者您可以釋放現有的並重新創建。
或者,如果是@property,您可以:
self.indexContent = [NSMutableArray array]; // not +new!!
或者,在該方法中:
[indexContent release];
indexContent = [NSMutableArray new];
如果您調用 function 的次數更多,那么您將泄漏 memory,因為您沒有從先前的調用中釋放已分配的 memory。 簡單的檢查是這樣的:
if(indexContent)
[indexContent release]
閱讀 Apple 的 memory 管理文檔會對您有很大幫助。
環繞代碼檢查 nil,如果它是 nil,則分配數組
//check if it has been allocated
if(indexContent == nil)
{
indexContent = [[NSMutableArray alloc] init];
int numberOfEntries = [noteBookContent count]/3;
for (int k=0; k < numberOfEntries; k++) {
IndexItem *newItem = [[IndexItem alloc] init];
newItem.itemTitle = [noteBookContent objectAtIndex:(k*3)];
newItem.itemPage = k;
if (![[noteBookContent objectAtIndex:(k*3)] isEqualToString:@""]) {
[indexContent addObject:newItem];
}
[newItem release];
}
}
這取決於。 indexContent 是否聲明為保留@property? 如果是這樣,運行時將負責釋放先前的數組。 如果沒有,並且您沒有明確釋放它,那么是的,它會泄漏。
您還應該確保在您的dealloc
方法中釋放 indexContext。
編輯:正如@bbum 提到的,你必須使用點符號。 self.indexContent = <whatever>;
忽略這一點是我的壞事。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.