Objective c 数组中对象的内存泄漏

Objective c 数组中对象的内存泄漏,objective-c,memory-leaks,Objective C,Memory Leaks,我已经开始在发布前清理我的应用程序——使用“仪器”泄漏分析仪 我发现了一个无法堵住的漏洞。因此,我构建了一个简单的项目来说明这个问题。请参阅下面的代码。我在视图上放置了一个按钮来测试启动程序“test”。它总是会产生泄漏 首先是名为“theObj”的对象的头和代码 现在是视图控制器 #import <UIKit/UIKit.h> #import "theObj.h" @interface LeakAnObjectViewController : UIViewController {

我已经开始在发布前清理我的应用程序——使用“仪器”泄漏分析仪

我发现了一个无法堵住的漏洞。因此,我构建了一个简单的项目来说明这个问题。请参阅下面的代码。我在视图上放置了一个按钮来测试启动程序“test”。它总是会产生泄漏

首先是名为“theObj”的对象的头和代码

现在是视图控制器

#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];
}  
#导入
#导入“theObj.h”
@接口LeakAnObjectViewController:UIViewController{
NSMutableArray*arobjects;
}
-(i)试验;
@结束
#导入“LeakAnObjectViewController.h”
@LeakAnObjectViewController的实现
-(IBAction)测试{
if(arobjects==nil)
arobjects=[[NSMutableArray alloc]init];
NSString*aStr=@“第一”;
[arobjects addObject:[[theobject alloc]initWithObjects:asr]];
[arrObjects removeAllObjects];
}  

您分配了该对象,这意味着您拥有它。然后将其交给数组,这意味着数组也拥有它。然后数组将其删除,因此您是唯一的所有者。但是你不再有对该对象的引用,所以你不能释放它,所以它只是泄漏了。

有人真的需要学习。特别是与所有权等有关。

Objective-C?您可能应该标记语言(我会,但我不确定我猜的是否正确)。在提问时,您应该使用更多的标记,这会告诉其他人您正在使用的技术,并提高获得答案的机会。因此,我更改了代码,试图释放有问题的字符串-但它仍然会产生泄漏。-(iAction)测试{if(arrObjects==nil)arrObjects=[[NSMutableArray alloc]init];NSString*aStr=@“first”;[arrObjects addObject:[[theobject alloc]initWithObjects:aStr];[arrObjects removeAllObjects];[aStr release];@manateman:嗯,你刚刚为
aStr
添加了一个版本。你的
[theobject>[theobject]
仍然无法与发布平衡。您需要执行
id temp=[[theObj alloc]initWithObjects:aStr];[arObjects addObject:temp];[temp release]
。好的,Chuck-非常感谢-这解决了测试项目中的漏洞。我真的没有任何借口不去看树,除了森林挡住了我的去路。现在我要回到现实世界,看看我是否能为我的应用程序做些什么。请相信我-我今天一个人读了三遍-更不用说过去的遭遇了。几楼我的意思是,如果我添加行[aStr release];它没有效果-仍然会泄漏。您需要确保在适当的情况下使用自动释放,在适当的情况下保留,等等。如果您只是使用alloc/init而没有自动释放,那么您需要确保在使用该对象后,您周围有一个引用,您可以自己释放它。当你是这样做的。如果你把东西放在集合中,你不应该这样做。这在我链接的规则中都有涉及。
@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
#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];
}