2010-03-08 54 views
0

我有一個問題,不好訪問。我已經轉身在NSZombieEnabled,但無法弄清楚爲什麼會造成這個問題。 如何定義cartInstance數組,您可以在下面的函數中看到。 這是一個帶有幾個NSMutableDictionaries的NSMutableArray 每次我的計數器達到13時都會發生錯誤。 然後,我得到一個不好的訪問權限和消息,如標題所示。 下面是一些代碼:「 - [CFNumber intValue]:發送到解除分配的實例的消息」,不知道

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

}

任何人都可以幫我嗎? 在此先感謝。你有

回答

3

的一個問題是在這裏:

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

這種分配一個自動釋放的NSNumber,但你手動釋放它以後。不要這樣做。

嘗試在您的應用上使用「構建&分析」;它會告訴你這樣的內存管理問題。

+0

Doh!非常感謝你。我很新的objective-c .. :-) 謝謝 – 2010-03-08 04:18:05

1

總之,不要發佈任何你沒有分配的東西。由於您沒有爲newAmount調用「alloc」。你也不應該叫釋放。

相關問題