2012-12-11 74 views
0
- (NSArray *) makeKeyValueArray: (NSArray *) arr 
{ 
    NSMutableArray *result = [[NSMutableArray alloc] init]; 
    for(int i = 0; i < [arr count]; i++) 
    { 
     [result addObject:[[KeyValue alloc] initWithData:[arr objectAtIndex:i] :[arr objectAtIndex:i]]]; 
    } 
    return result; 
} 

儀器是顯示在上面的代碼188層的泄漏,這是爲什麼?任何人都可以請給我解釋一下嗎?爲什麼儀器是顯示在下面的代碼這麼多的泄漏?

+0

'initWithData ::'是一個可怕的方法名。給定類名,'initWithKey:value:'怎麼樣? – bbum

回答

5
- (NSArray *) makeKeyValueArray: (NSArray *) arr 
{ 
    NSMutableArray *result = [[NSMutableArray alloc] init]; 
    for(int i = 0; i < [arr count]; i++) 
    { 
     id obj = [[KeyValue alloc] initWithData:[arr objectAtIndex:i] :[arr objectAtIndex:i]]; // obj reference count is now 1, you are the owner 
     [result addObject:obj]; //reference count is now 2, the array is also an owner as well as you. 
     [obj release];// reference count is now 1, you are not the owner anymore 
    } 
    return [result autorelease]; 
} 

看看Basic Memory Management Rules

你必須放棄對象的所有權您擁有

+0

你能否詳細說明一下?我無法理解這個概念。 –

+1

你分配鍵值,但你永遠不會釋放它。正如本答案所示,您必須向您創建的對象發送「釋放」消息。 –

+0

@Parag它現在正在崩潰我的應用程序! –