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.
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: