[英]Memory management : release viewcontroller object after adding to NSMutableArray
I have a memory leak with below code. 下面的代码我有内存泄漏。 If I use
[sub release];
如果我使用
[sub release];
after adding sub to NSmutableArray(subViewController), Analyzer says "Inconrrect decrement of the reference count of an object that is not owned at this point by the caller" , when i remove [sub release]
then it says "Potential leak of an object allocated on xx line" 在向NSmutableArray(subViewController)添加sub之后,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 if I use autorelease Warning becomes "Object sent -autorelease too many times" Alson如果我使用自动释放警告变为“对象发送-autorelease太多次”
SubCategoryViewController *sub =[[[SubCategoryViewController alloc]
initwithServiceUrl:urlString andHeaderValue:
((PMCategory *)[self.data objectAtIndex:i]).categoryName]autorelease];
Added from comment: SubCategoryViewController Init method: 从评论中添加: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;
it is because you haven't followed proper naming convention of Objective c. 这是因为你没有遵循Objective c的正确命名约定。 Whenever you are writing any initialization function namingConvention is something like
每当你编写任何初始化函数时,namingConvention都是这样的
-(id) initFirstWordSecondWord{
}
means make first letter after init Capital. 意味着在init Capital之后发出第一个字母。
So change your initwithServiceUrl
to initWithServiceUrl
and your problem will be solved. 因此,将
initwithServiceUrl
更改为initWithServiceUrl
,您的问题将得到解决。 cheer up!!! 开心点!!!
If data
is a property with the retain
attribute then it is over retained, once by: 如果
data
是具有retain
属性的属性,那么它将被过度保留,一次为:
[[NSMutableArray alloc] init]
and once by the property setter. 一次由财产安装人员。
Change it to use the class convenience method that returns an autoreleased NSMutableArray
: 将其更改为使用返回自动释放的
NSMutableArray
的类便捷方法:
self.data = [NSMutableArray array];
Additionally the for loop can be written more clearly with fast enumeration: 另外,使用快速枚举可以更清楚地编写for循环:
for (PMCategory *category in self.data) {
SubCategoryViewController *sub =[[SubCategoryViewController alloc]
initwithServiceUrl:urlString
andHeaderValue:category.categoryName];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.