Memory Leak When Removing from NSArray?

Discussion in 'iOS Programming' started by Jokode, Jan 30, 2009.

  1. Jokode macrumors newbie

    Joined:
    Dec 14, 2008
    #1
    Hi,
    I have just noticed when testing my app against the Object Allocations tool, I am getting a ton of objects being allocated in the category of "CFArray (store-deque)".

    I have just isolated the problem down to this line:
    [myArray removeObjectAtIndex:0];

    This line is being called in my main engine on every loop cycle, so I am getting a lot of these being allocated.

    I have had a look around online but don't seem to be able to find a good explanation or a workaround. Does anyone have any idea why this is happened?

    Thanks,
    Joe.
     
  2. admanimal macrumors 68040

    Joined:
    Apr 22, 2005
    #2
    We would need to see the rest of your code to know what is happening. An object will be released when you remove it from the array, but if you have retained it more than necessary elsewhere, it will leak when you remove it from the array and no longer have a pointer to it.
     
  3. Jokode thread starter macrumors newbie

    Joined:
    Dec 14, 2008
    #3
    Thanks

    Thanks admanimal.

    I have just added a new line
    [[myArray objectAtIndex:0] release];
    [myArray removeObjectAtIndex:0];

    which has solved the problem - until I figure out where I am retaining it!

    Thanks again.
     
  4. admanimal macrumors 68040

    Joined:
    Apr 22, 2005
    #4
    If you are creating the objects you put into the array using an [[NSObjectName alloc] init...] style method, you should generally release the object right after you put it into the array, since they will already have a retain count of 1, which will be increased to 2 after being placed in the array.
     

Share This Page