0

我有一个 exc 错误访问的问题。我已经打开了 NSZombieEnabled,但不知道为什么会出现这个问题。cartInstance 数组是如何定义的,您可以在下面的函数中看到。这是一个带有多个 NSMutableDictionaries 的 NSMutableArray 每次我的计数器达到 13 时都会发生错误。然后我得到一个 exc bad access 和标题所示的消息。这是一些代码:

-(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.");
}

}

谁能帮我吗?提前致谢。

4

2 回答 2

3

您遇到的一个问题是:

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

这会分配一个自动释放的 NSNumber,但您稍后会手动释放它。不要这样做。

尝试在您的应用上使用“构建和分析”;它会给你指出这样的内存管理问题。

于 2010-03-08T03:19:53.277 回答
1

简而言之,不要释放任何你没有分配的东西。由于您没有为 newAmount 调用“alloc”。您也不应该调用 release 。

于 2010-03-08T03:42:19.247 回答