![](/img/trans.png)
[英]Adding custom defined objects to NSMutableArray overwrite the whole array
[英]Last array value overwrite when adding NSMutableArray into another NSMutableArray
NSMutableArray *no1=[[NSMutableArray alloc]init];
NSMutableArray *no2=[[NSMutableArray alloc]init];
for(int i=0;i<3;i++)
{
for (int j=0;j<=i;j++)
{
NSString *no_str=[NSString stringWithFormat:@"%d",j];
[no1 addObject:no_str];
}
[no2 addObject:no1];
[no1 removeAllObjects];
}
NSLog(@"Final:%@",no2);
我得到像这样的输出:
最终:((0,1,2),(0,1,2),(0,1,2))
但是我需要这样的输出:
最终:((0),(0,1),(0,1,2))
请任何人帮助我。
更新的代码:-
NSMutableArray *no1;
NSMutableArray *no2=[[NSMutableArray alloc]init];
for(int i=0;i<3;i++)
{
no1=[[NSMutableArray alloc]init];
for (int j=0;j<=i;j++)
{
NSString *no_str=[NSString stringWithFormat:@"%d",j];
[no1 addObject:no_str];
}
[no2 addObject:no1];
[no1 release];
}
NSLog(@"Final:%@",no2);
我假设您使用的是ARC,因此此代码可以正常工作。
NSMutableArray *no1;
NSMutableArray *no2=[[NSMutableArray alloc]init];
for(int i=0;i<3;i++)
{
no1=[[NSMutableArray alloc]init];
for (int j=0;j<=i;j++)
{
NSString *no_str=[NSString stringWithFormat:@"%d",j];
[no1 addObject:no_str];
}
[no2 addObject:no1];
}
NSLog(@"Final:%@",no2);
编辑:即使您分配init no1的结果将是相同的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.