Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iteration over NSMutableArray objects. Best Practice

in my app I have several loops where accessing to the members of a NSMutableArray to use them. Here an example:

for (a=0;a<[items count];a++)
{
iItem *item = [[items objectAtIndex:a] autorelease];

    [page.view addSubview:item];

NSLog(@"Item Added: %d\nItem Frame X:%f Y:%f W:%f H:%f",item.itemId,item.frame.origin.x,item.frame.origin.y,item.frame.size.width,item.frame.size.height);

    [item setDelegate:page];

    if ([[items objectAtIndex:a] zOrder] == 1)
        [page.view sendSubviewToBack:item];
    else 
        [page.view bringSubviewToFront:item];

//[item release];
//item = nil;

}

My question is if I've created the iItem objects in a different method using alloc/init and release after adding it to the MutableArray, is necessary use a release over iItem created in the loop, after being used?

Thanks.

like image 650
NemeSys Avatar asked Dec 01 '22 23:12

NemeSys


1 Answers

As omz already pointed out, you are over-releasing your items. If you only have items of type iItemin your array, you can use fast enumeration:

for (iItem *item in items)
{
    [page.view addSubview:item];

    NSLog(@"Item Added: %d\nItem Frame X:%f Y:%f W:%f H:%f",item.itemId,item.frame.origin.x,item.frame.origin.y,item.frame.size.width,item.frame.size.height);

    [item setDelegate:page];

    if ([item zOrder] == 1)
        [page.view sendSubviewToBack:item];
    else 
        [page.view bringSubviewToFront:item];
}
like image 101
tilo Avatar answered Dec 18 '22 22:12

tilo