内存管理:添加到NSMutableArray后释放viewcontroller对象

时间:2012-01-26 03:41:20

标签: iphone memory-management analyzer

我的内存泄漏代码如下。如果我在向NSmutableArray(subViewController)添加sub后使用[sub release];,则Analyzer表示“调用者不在此时拥有的对象的引用计数的不正确减少”,当我删除[sub release]然后它说“在xx行分配的对象的潜在泄漏”

for (int i=0; i<[self.data count]; i++) {

   SubCategoryViewController *sub =[[SubCategoryViewController alloc] 
           initwithServiceUrl:urlString andHeaderValue: 
          ((PMCategory *)[self.data objectAtIndex:i]).categoryName];

   [[AppDelegate sharedAppDelegate].viewController.subViewControllers addObject:sub];
   [sub release];


}

Alson如果我使用自动释放警告变为“对象发送 - 自动释放太多次”

SubCategoryViewController *sub =[[[SubCategoryViewController alloc] 
           initwithServiceUrl:urlString andHeaderValue: 
          ((PMCategory *)[self.data objectAtIndex:i]).categoryName]autorelease];

从评论中添加: SubCategoryViewController Init方法:

@property (nonatomic, retain) NSMutableArray *data;
@property (nonatomic, copy) NSString *headerText;
@synthesize data = _data;
@synthesize headerText=_headerText;

...

self = [super init];
if (self) {
    self.data = [[NSMutableArray alloc] init] ;
    self.headerText =headerValue;
    self.serviceURL =serviceU;
    self.firstLoad = YES;
}
return self;

2 个答案:

答案 0 :(得分:2)

这是因为您没有遵循Objective c的正确命名约定。每当你编写任何初始化函数时,namingConvention就像是

-(id) initFirstWordSecondWord{
}

表示在init Capital之后填写第一个字母。

因此,将initwithServiceUrl更改为initWithServiceUrl,您的问题就会得到解决。 振作起来!!!

答案 1 :(得分:0)

如果data是具有retain属性的属性,则会过度保留,一次为:

[[NSMutableArray alloc] init]

一次由财产制定者。

更改它以使用返回自动释放的NSMutableArray

的类便捷方法
self.data = [NSMutableArray array];

此外,使用快速枚举可以更清楚地编写for循环:

for (PMCategory *category in self.data) {
    SubCategoryViewController *sub =[[SubCategoryViewController alloc] 
        initwithServiceUrl:urlString
        andHeaderValue:category.categoryName];