我在这里尝试将多个数组添加到一个NSMutableArray中 实际上我正在添加具有不同值的相同数组多次到一个NSMutable数组 这个代码:
NSMutableArray* wordsArray =[[NSMutableArray alloc] init ];
NSMutableArray* meaningsArray=[[NSMutableArray alloc]init];
NSMutableArray* wordsArrayTemp=[[NSMutableArray alloc]init];
NSMutableArray* meaningsArrayTemp=[[NSMutableArray alloc]init ];
NSMutableArray* allWords =[[NSMutableArray alloc]initWithCapacity:2];
NSMutableArray* allMeanings=[[NSMutableArray alloc]initWithCapacity:2];
for(int i=0;i<2;i++)
{
int wordsCounter=0;
[wordsArrayTemp removeAllObjects];
[meaningsArrayTemp removeAllObjects];
for(NSString *tmp in wordsArray)
{
NSString *meaning =[meaningsArray objectAtIndex:wordsCounter++];
subtmp= [ tmp substringWithRange:NSMakeRange(0,1)];
if([currentTable isEqualToString:@"arabicToEnglish"])
{
if([subtmp isEqualToString:[arabicLetters objectAtIndex:i]])
{
[wordsArrayTemp addObject:tmp];
[meaningsArrayTemp addObject:meaning];
}
}
else
if([subtmp isEqualToString:[englishLetters objectAtIndex:i]])
{
[wordsArrayTemp addObject:tmp];
[meaningsArrayTemp addObject:meaning];
}
}
[allWords insertObject:wordsArrayTemp atIndex:i];
// [allWords addObject: wordsArrayTemp];
[allMeanings addObject:meaningsArrayTemp];
NSLog(@"all words count%i",[[allWords objectAtIndex:i] count]);
}
问题: 这里假设的行为是在allWords数组中有2个不同的值。 但实际发生的是,2个值用最后一个索引值填充相同的值。 我的意思是[allWords objectAtIndex:0]应该有2000个对象,[allWords objectAtIndex:1]应该有3000个,但是它们都有3000个对象会发生什么!!
我在这里错过了什么?!! 日Thnx
答案 0 :(得分:1)
将对象添加到数组时,不会复制对象。你只需保存其内存地址。
基本上,您将相同的临时数组添加到父数组中。并且您对所有阵列进行了相同的操作。
也许这段展开的循环代码会让它更清晰一些。
// create new array on a specific memory address. let's say this address is 0x01
NSMutableArray* wordsArrayTemp=[[NSMutableArray alloc]init];
// first iteration of your loop
// remove all objects from array at memory address 0x01
[wordsArrayTemp removeAllObjects];
// add objects to the array at address 0x01
[wordsArrayTemp addObject:tmp];
// insert array (still at address 0x01) to the parent array
[allWords insertObject:wordsArrayTemp atIndex:i];
// your allWords array now looks like this: {array@0x01}
// second iteration of your loop
// remove all objects from array at memory address 0x01!!! (still the same array as in the first iteration)
// since it's the same array all objects from the array at [allWords objectAtIndex:0] are removed too
[wordsArrayTemp removeAllObjects];
// add objects to the array at address 0x01
[wordsArrayTemp addObject:tmp];
// insert array (still at address 0x01) to the parent array
[allWords insertObject:wordsArrayTemp atIndex:i];
// your allWords array now looks like this {array@0x01, array@0x01}
解决方案非常简单。
在for循环的开头,而不是从数组中删除allObjects,创建新的数组 只需替换
[wordsArrayTemp removeAllObjects];
[meaningsArrayTemp removeAllObjects];
带
wordsArrayTemp = [NSMutableArray array];
meaningsArrayTemp = [NSMutableArray array];
答案 1 :(得分:0)
尝试同时添加一个数组:
[[allWords array] addObject:wordsArray.array];
希望它会有所帮助
答案 2 :(得分:0)
试试这个: -
[allWords insertObject:[wordsArrayTemp copy] atIndex:i];
它应该有用。