简体   繁体   中英

Does this cause a memory leak?

I normally initialize all class members inside of init method and use setter to set those variables:

 //Question.m file
 -(id)init{
      self = [super init];
      if (self == nil) {

      }
      else {
           tid = [[NSString alloc]initWithString:@""];
           title = [[NSString alloc]initWithString:@""];
      }
      return self;
 }

And I am doing something like this:

 //OtherClass.m file
 Question *q = [[Question alloc]init];
 q.tid = aString;
 q.title = bString;
 [questions addObject:q];

I also release everything in dealloc method in the Question class. If I test the memory leaking using Instruments then it shows memory leaking but I don't see why. What is the best way to initialize a class without causing any memory leaking?

Golden rule is if you are allocating an object by yourself rather than using any static/factory method then you yourself have to take care of releasing it also.

In your case I can see that you are allocating Question using alloc. So you have to make sure to release it. Add this line after calling addObject and it should solve your problem of memory leaking.

[q release];

q.tid and q.title are allocated and initialized in the init , then they are overwritten by the second piece of code.

They need to be released first.

The problem is almost surely the following two lines:

q.tid = aString;
q.title = bString;

After that the tid and title pointers in the q object that were allocated in the init method are now dangling.

Try creating the following setters instead:

//Question.m
-(void)setTID:(NSString)string {
    if (string == tid)
        return;

    [ tid release ];
    tid = [ string retain ];
}

-(void)setTitle:(NSString)string {
    if (string == title)
        return;

    [ title release ];
    title = [ string retain ];
}

Then do the following instead:

//OtherClass.m file
Question *q = [[Question alloc]init];
[ q setTID: aString ];
[ q setTitle: bString ];

I believe it's something along these lines (If anyone wishes to correct me, please do). Also make sure you release tid and title in Question's dealloc.

Edit: Updated setters as noted in comments.

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