我正在使用以下代码将元素动态存储在数组中,并在以后检索它
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"
最佳答案
如果每次在初始化内存时都在循环内部进行初始化,则在for循环上方分配testimonialsArray = [[NSMutableArray alloc]init];
,最终值只有在finally输出时才执行,就像
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);