我使用以下代码动态地将元素存储在数组中并稍后检索
for (int i = 0; i< [companyNames count]; i++){
testimonialsArray = [[NSMutableArray alloc]init];
testimonialsComplementedArray = [[NSMutableArray alloc]init];
[testimonialsArray addObject:companyNames[i] ];
[testimonialsComplementedArray addObject:texts[i]];
NSLog(@"Compliments %@",testimonialsComplementedArray);
}
但它只打印已添加到数组的最后一个副本。如何检索所有元素?
以下是公司名称,
"General Marketing Company",
"United Enterprises, Chennai",
"Hari Match Industries"
答案 0 :(得分:1)
testimonialsArray = [[NSMutableArray alloc]init]; // have to init out side the loop
testimonialsComplementedArray = [[NSMutableArray alloc]init]; // have to init out side the loop
for (int i = 0; i< [companyNames count]; i++){
[testimonialsArray addObject:companyNames[i] ];
[testimonialsComplementedArray addObject:texts[i]];
}
NSLog(@"Compliments %@",testimonialsComplementedArray);
答案 1 :(得分:1)
如果你在每次内存初始化的时候在循环内部启动,那么在for循环上面分配testimonialsArray = [[NSMutableArray alloc]init];
,所以最后的值只能在最后得到输出,就像
testimonialsArray = [[NSMutableArray alloc]init];
testimonialsComplementedArray = [[NSMutableArray alloc]init]
for (int i = 0; i< [companyNames count]; i++){
[testimonialsArray addObject:companyNames[i] ];
[testimonialsComplementedArray addObject:texts[i]];
}
NSLog(@"Compliments %@",testimonialsComplementedArray);
答案 2 :(得分:1)
每次都在for循环中分配可变数组因为它初始化数组并且每次都在其中添加对象。总是更好地在ViewDidLoad方法中分配任何对象。
答案 3 :(得分:1)
试试这样。
testimonialsArray = [[NSMutableArray alloc]init];
testimonialsComplementedArray = [[NSMutableArray alloc]init];
for (int i = 0; i< [companyNames count]; i++){
[testimonialsArray addObject:companyNames[i] ];
[testimonialsComplementedArray addObject:texts[i]];
}
NSLog(@"Compliments %@",testimonialsComplementedArray);