views:

46

answers:

2

I have a class, that basically manages core data. inserts deletes and updates data. I initialize this class like so

- (id)init
{
    self = [super init];
    if (self) {
        self.itemList = [NSDictionary dictionaryWithObjectsAndKeys: // <== LEAKS
                    ITEMURL1, KEY1,
                    ITEMURL2, KEY2,
                    ITEMURL3, KEY3,
                    ITEMURL4, KEY4,
                    ITEMURL5, KEY5,
                    nil];
        self.storedItems = [[NSMutableArray alloc] init]; // <== LEAKS

    }
    return self;
}


- (void)dealloc {
    [storedItems release];
    [super dealloc];
}

I have taken care that I release every object carefully. whenever it is allocated, But I still seem to get leaks at init when I run the app in Instruments.

what is going on? am I doing something wrong?

A: 

Regarding storedItems:

if storedItems is declared as

@property (nonatomic, retain) NSMutableArray *storedItems;

(the retain part is the important) then you need to do:

NSMutableArray *storedItems_ = [[NSMutableArray alloc] init];
self.storedItems = storedItems_;
[storesItems_ release];

alloc + init will cause your object9¥'s retain count go to 1. Then using self.xxx will retain it again as declared in the attributes of your property. Hence it will be 2. This will not happen with assign

nacho4d
Thanks that stopped storedItems from leaking. I don't really get it though, why do this step? isn't it the same as what I was doing?
Rupert
itemList still leaks.. is it because of the constants?
Rupert
There is a explanation here: http://nacho4d-nacho4d.blogspot.com/2010/08/notes-on-memory-management-in-objective.html . And regarding itemList, how itemList is declared?
nacho4d
@Rupert itemList still leaks because you aren't releasing it. Your posted `dealloc` only releases storedItems. Presumably itemList is declared with the 'retain' attribute as well.
imaginaryboy
+1  A: 

You need to add [itemList release] to your dealloc method (assuming you've got "retain" in the property declaration.

As for storedItems, if you've got retain in the property declaration, you should autorelease it when you assign it:

self.storedItems = [[[NSMutableArray alloc] init] autorelease];

Or more concisely, but equivalently:

self.storedItems = [NSMutableArray array];
Andrew Madsen
If you're using properties anyway, prefer `self.itemList = nil; self.storedItems = nil;`.
tc.