views:

244

answers:

2

Hey there, i have a problem with a exc bad access. I already turned in NSZombieEnabled, but cannot figure out why this problem will be caused. How the cartInstance Array is defined you can see below in the following function. It's a NSMutableArray with several NSMutableDictionaries The error occurs every time my counter i reaches 13. Then i get a exc bad access and the message as shown in the title. Here is some code:

-(void)addToCart:(NSDictionary *) article{
if(article!=nil){

    NSString * amount    = @"amount";
    NSString * articleId = @"articleId";
    NSString * detailKey = @"detailKey";



    NSString *curId = [article objectForKey:@"articleId"];

    //check if article already in shopping cart
    if([cartInstance count]>0)
    {
        for(int i=0;i<[cartInstance count];i++) {
            NSString *tempStr = [[cartInstance objectAtIndex:i] objectForKey:articleId];
            if([tempStr isEqual:curId]) {

                NSNumber *newAmount = [[cartInstance objectAtIndex:i] objectForKey:amount];
                NSLog(@"AddtoCart");
                int tempInt = [newAmount intValue]+1;//Here is where the magic happens
                newAmount = [NSNumber numberWithInt:tempInt];
                [[cartInstance objectAtIndex:i] setObject:newAmount forKey:amount];
                [newAmount release];
                return;
            }
        }
    }


    NSDictionary *details = article;
    NSDictionary *shoppingItem = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                  [NSNumber numberWithInt:1],amount,
                                  curId,articleId,
                                  details,detailKey,
                                  nil];
    [shoppingItem retain];

    [cartInstance addObject:shoppingItem];
    id obj;
    NSEnumerator * enumerator = [cartInstance objectEnumerator];
    while ((obj = [enumerator nextObject])) NSLog(@"%@", obj);

}
else{
    NSLog(@"Error: Could not add article to shoppingcart.");
}

}

Can anyone help me out? Thanks in advance.

+3  A: 

One problem you've got is here:

            newAmount = [NSNumber numberWithInt:tempInt];
            [[cartInstance objectAtIndex:i] setObject:newAmount forKey:amount];
            [newAmount release];

This allocates an autoreleased NSNumber, but you release it manually later. Don't do this.

Try using "Build & Analyze" on your app; it'll point you to memory management problems like this.

Nicholas Riley
Doh! Thank you very much. I'm pretty new to objective-c.. :-)Thanks
Simon D.
A: 

In short, don't release anything that you didn't allocate. Since you didn't call "alloc" for newAmount. You shouldn't call release as well.

Mugunth Kumar