Adam Johnson
Adam Johnson

Reputation: 2216

Obj-C: Properly releasing allocated objects in loop

Hopefully I can explain this well. Assume the following:

@interface ClassA : NSObject {
   NSMutableArray firstArray;
   NSArray secondArray;
}

#import "ClassA"
@interface ClassB : NSObject {
   ClassA classAobject;
}

Then in some other part of the program 'Psuedo-code' accessing dictionary keys like:

NSMutableArray* sample = [[NSMutableArray alloc] init];
for (keys in Data)
{
    ClassA* aObj = [[ClassA alloc] initWith: objectForKey:@"KeyHere" andWith:@"Key2Here"];

    ClassB* bObj = [[ClassB alloc] init];
    [bObj setClassAObj: aObj];

    [sample addObject: bObj];
}
Singleton* single = [Singleton single];
[single setArray: sample];

My question is with the ClassA and ClassB objects created inside the loop and the array to store them outside of the loop. Am I leaking memory here, by not releasing them? If I do release them, how can I do so in a way that I wont lose the reference to them in the singleton to which I am storing the 'sample' array?

If it matters, the Singleton array to which it is being stored is allocated and initialized in the "init" method of the class.

Upvotes: 0

Views: 264

Answers (2)

David V
David V

Reputation: 11699

NSMutableArray performs retain and release on objects as they are added and removed respectively. So you get one retain for the alloc, and then a second retain for the add. When the array is destroyed, it will release one. That leaves you with a retain count of 1.

You can make these autorelease. I believe it improves performance to have the memory released together and is the recommended approach.

Upvotes: 1

Flyingdiver
Flyingdiver

Reputation: 2142

Adding objects to an array retains the objects. So you need to release them after you add them (if not autoreleased). Similarly, you need to make sure that the @properties for the instance variable array (in Singleton) is set to retain so that the sample array is retained when set in the singleton. Then you need to release sample as well.

Also, your instance variables need to be pointers:

@interface ClassA : NSObject {
   NSMutableArray *firstArray;
   NSArray *secondArray;
}

#import "ClassA"
@interface ClassB : NSObject {
   ClassA *classAobject;
}

Upvotes: 1

Related Questions