2016-05-30 48 views
0

在mutableArray中添加新元素之前添加的元素(从字典中提取)也用新添加的元素替换。nsmutableArray用最后添加的对象替换元素

for (int i = 0; i < [_ContentArray count]; i++){ 

    if ([[[_ContentArray objectAtIndex:i]objectForKey:@"type"] isEqualToString:@"video"]) { 

     NSString *videoUrl = [[_ContentArray objectAtIndex:i]objectForKey:@"url"]; 

     NSString *videoName = [[_ContentArray objectAtIndex:i]objectForKey:@"title"]; 


     [_videoContentDict setValue:videoUrl forKey:@"url"]; 
     [_videoContentDict setValue:videoName forKey:@"title"]; 

     [_videoArray addObject:_videoContentDict]; 


     NSLog(@"%@%%",_videoArray); 

    } 

    } 

这里 - _videoContentDict是mutableDictionary _videoArray是mutableArray

+0

你有两个分配的内存?为什么您使用字典在另一个数组中添加值?你可以使用NSObject来存储值。 –

+0

你在,我有一本字典。您将该字典反复添加到'videoArray'。当您更改字典时,该更改将反映在数组中的所有元素上,因为所有元素都是对同一字典的引用。 – Paulw11

回答

1

我想你每次旧的对象与新对象到NSMutableArray。因为您在for循环之外分配了NSMutableDictionary

所以使像下面的代码回路侧的NSMutableDictionary的alloc初始化:

for (int i = 0; i < [_ContentArray count]; i++){ 

    if ([[[_ContentArray objectAtIndex:i]objectForKey:@"type"] isEqualToString:@"video"]) { 

     _videoContentDict = [[NSMutableDictionary alloc]init]; 
     NSString *videoUrl = [[_ContentArray objectAtIndex:i]objectForKey:@"url"]; 

     NSString *videoName = [[_ContentArray objectAtIndex:i]objectForKey:@"title"]; 


     [_videoContentDict setValue:videoUrl forKey:@"url"]; 
     [_videoContentDict setValue:videoName forKey:@"title"]; 

     [_videoArray addObject:_videoContentDict]; 


     NSLog(@"%@%%",_videoArray); 

    } 

    }