简体   繁体   中英

Is this a memory leak?

I have the following 2 code snippets. Assume I have a Parent class and in Parent.h class I have

@property (retain) NSMutableArray *childrens;

and I have synthesize it in the .m file correctly. assume in Parent.m file

-(void) dealloc

{

 [childrens release];
 [super dealloc];

}

In another class I declare like this.

1.

Parent *p = [[Parent alloc] init];
p.chidlrens = [[NSMutableArray alloc] init];
// do some other stuff

2.

Parent *p = [[Parent alloc] init];
NSMutableArray *childArray = [[NSMutableArray alloc] init];
p.childrens = childArray;
[childArray release];

From above 2 methods is there a leak in method 1?

是的,方法1中存在泄漏。您分配NSMutableArray但不释放它。

While not answering your question, I'd recommend having Parent init and alloc the array in it's Init method, so your code elsewhere doesn't have to worry about checking if it's already created and doing it. Then you don't need to have the classes that use Parent worry about Parent's memory management - Parent can do it.

the general rule is to release anything your doing alloc, init on.

but do a build + analyze to get some 'potential' leaks. if you want to be 100% sure, run it though leaks

To check where is leakage you can without somebody help. For example, use any plugins for that. I use deleaker and know exactly where is a memory leak.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM