内存管理 :添加到NSMutableArray后释放viewcontroller对象
-
14-11-2019 - |
题
我有一个内存泄漏与下面的代码。如果我使用 [sub release];
将sub添加到NSmutableArray(subViewController)后,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如果我使用autorelease警告成为 "发送对象-自动释放太多次"
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;
解决方案
这是因为你没有遵循Objective c的正确命名约定。每当你写任何初始化函数namingConvention是这样的
-(id) initFirstWordSecondWord{
}
意思是在init资本之后做第一个字母。
所以改变你的 initwithServiceUrl
到 initWithServiceUrl
你的问题就会解决。振作起来!!!
其他提示
如果 data
是一个拥有 retain
属性则结束保留,一次通过:
[[NSMutableArray alloc] init]
一次由属性设置者。
将其更改为使用返回autoreleased的类便利方法 NSMutableArray
:
self.data = [NSMutableArray array];
此外,for循环可以用快速枚举写得更清楚:
for (PMCategory *category in self.data) {
SubCategoryViewController *sub =[[SubCategoryViewController alloc]
initwithServiceUrl:urlString
andHeaderValue:category.categoryName];
不隶属于 StackOverflow