2016-02-18 20 views
0

我用下面的代码来存储数组元素动态所有数组元素,并在以后检索NSMutableArray的不打印

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" 

回答

1

分配testimonialsArray = [[NSMutableArray alloc]init];在上面的for循环,如果你每次内存将用来初始化时间用来初始化的循环中,所以最终值只有你上在最终输出,不喜欢

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); 
+0

它在屏幕上显示相同的推荐信息三次 –

+0

它显示基于您的'companyNames'计数bro的详细信息,您需要除了其他任何东西 –

+0

我想你忘记分配'testimonialsComplementedArray'的内存,检查更新的答案bro –

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); 
+0

它打印相同的值三次而不是唯一的 –

+0

它必须显示在ui中的证词细节,赞美。 –

+0

@Stanly nslog如何显示。它的值是否正确? – anhtu

1

你每次分配可变数组在,因为它的初始化数组循环,并在everytim添加对象e。最好在ViewDidLoad方法中分配任何对象。

+0

是否有可能添加循环以外的对象? –

+0

对于每个索引的对象,您必须添加for循环。 –

+0

请你详细说明一下吗? –

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); 
+0

在ui上,同样的细节印三次 –

+0

你能告诉我什么是在公司名称,文本数组中有什么数据 –

+0

我已更新我的问题 –