2010-06-25 61 views
0

我已經開始在發佈之前清理我的應用程序 - 使用「Instruments」泄漏分析器。陣列中物體的內存泄漏

我發現了泄漏,我無法插入。所以我建了一個簡單的項目來說明問題。請參閱下面的代碼。我在視圖上放了一個按鈕來測試程序「測試」。它總是會產生泄漏。

首先首部和代碼名爲 「theObj」

#import <Foundation/Foundation.h> 


@interface theObj : NSObject { 

的NSString * theWord的對象; } @property(nonatomic,retain)NSString * theWord;現在視圖控制器

#import <UIKit/UIKit.h> 
#import "theObj.h" 

@interface LeakAnObjectViewController : UIViewController { 
NSMutableArray* arrObjects; 
} 
    - (IBAction)test; 
@end 

#import "LeakAnObjectViewController.h" 

@implementation LeakAnObjectViewController 

- (IBAction)test { 
if (arrObjects == nil) 
    arrObjects = [[NSMutableArray alloc] init]; 

NSString* aStr = @"first"; 
[arrObjects addObject:[[theObj alloc] initWithObjects:aStr]]; 
[arrObjects removeAllObjects]; 
} 
+1

Objective-C?你應該標記語言(我會,但我不知道我猜對了)。 – 2010-06-25 20:28:26

+0

在提問時,您應該使用更多標籤,這會告訴您正在使用的其他技術並提高獲得答案的機會。 – VoodooChild 2010-06-25 20:30:23

回答

0

@end 

#import "theObj.h" 


@implementation theObj 
@synthesize theWord; 

-(id) initWithObjects: (NSString *) aWord; 
{ 
if (self = [super init]){ 
    self.theWord = aWord; 
} 
return self; 
} 

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

@end 

您的Alloc的對象,這意味着你擁有它。然後你將它提供給數組,這意味着該數組也擁有它。然後數組將它移除,所以你是唯一的所有者。但是你不再有對象的引用,所以你不能釋放它,所以它只是泄漏。

+0

所以我改變了代碼,試圖釋放有問題的字符串 - 但它仍然會產生泄漏。 (IBAction)測試{arrObjects == nil} arrObjects = [[NSMutableArray alloc] init]; NSString * aStr = @「first」; [arrObjects addObject:[[theObj alloc] initWithObjects:aStr]]; [arrObjects removeAllObjects]; [aStr release]; – user266429 2010-06-25 20:50:58

+0

@manateeman:恩,你剛剛添加了'aStr'的一個版本。您的'[theObj alloc]'仍然與版本不兼容。你需要做'id temp = [[theObj alloc] initWithObjects:aStr]; [arrObjects addObject:temp]; [臨時發佈];'。 – Chuck 2010-06-25 20:58:19

+0

行查克 - 非常感謝 - 解決了測試項目中的泄漏。除了森林阻礙之外,我真的沒有任何理由不去看那棵樹。現在我將回到現實世界,看看我能否爲我的應用程序做一些好事。 – user266429 2010-06-25 21:12:22

0

有人真的需要學習the rules around memory management。具體而言,因爲它涉及所有權等。

+0

請相信我 - 今天我已經閱讀了3次 - 更不用說過去的遭遇了。如果我添加行 [aStr release]; 它沒有影響 - 仍然泄漏。 – user266429 2010-06-25 21:00:02

+0

您需要確保在適當的情況下使用autorelease,在適當的地方保留等。如果您只是使用alloc/init而不進行自動釋放,那麼在完成這些操作後,您需要確保有參考資料,以便可以發佈它自己。當你這樣做時,你完全擁有該物品。如果你把東西收藏起來,你不應該這樣做。這些都包含在我鏈接的規則中。 – jer 2010-06-25 21:52:59