-1

在这里,我从数组中cityName1获取了城市名称,如 Piscataway、Iselin、Broklyn 等,我需要将值放入一个名为.tgpList1item5

上述迭代获取了 133 条记录。以下代码仅存储最后一条记录cityName1,而不是整个城市名称列表,尽管在循环内。

我尝试了很多方法,但我错过了一些东西。

tgpList1是一个数组。 tgpDAO是一个 NSObject 有两个对象NSString *airportCodeNSString *cityName

NSArray *item5 = [[NSArray alloc]init]; 
for (int currentIndex=0; currentIndex<[tgpList1 count]; currentIndex++)
{
    tgpDAO *tgpTable = (tgpDAO *)[self.tgpList1 objectAtIndex:currentIndex];
    NSLog(@"The array values are %@",tgpList1);

    NSString *cityName1 = tgpTable.cityName;

    item5 =[NSArray arrayWithObjects:cityName1, nil];
}
4

3 回答 3

0

代替

item5 =[NSArray arrayWithObjects:cityName1, nil];

利用

[item5 addObject:cityName1];

还有更多方法可以实现这一目标。但是,这是为此目的而设计的,并且从我的观点来看,这是最“可读”的。

如果需要先清除item5的内容然后调用

[item5 removeAllObjects]; 

就在 for 循环之前。

您在做什么:arrayWithObjects 总是创建一个新数组,该数组由作为参数传递给它的对象组成。如果您不使用 ARC,那么您的代码会造成严重的内存泄漏,因为 arrayWithObjects 在每个循环中创建并保留一个对象,并且在下一个循环中,对刚刚创建的数组对象的所有引用都会丢失而不会被释放. 如果您执行 ARC,那么您不必担心这种情况。

于 2012-09-11T07:53:56.753 回答
0

使用可变数组。

{

   NSMutableArray *item5 = [[NSMutableArray alloc]initWithArray:nil];
   for (int currentIndex=0; currentIndex<[tgpList1 count]; currentIndex++) {            

       tgpDAO *tgpTable = (tgpDAO *)[self.tgpList1 objectAtIndex:currentIndex];
       NSLog(@"The array values are %@",tgpList1);
       NSString *cityName1 = tgpTable.cityName;
       [item5 addObject:cityName1];

   }
}
于 2012-09-11T07:55:09.150 回答
0
NSMutableArray *myCities = [NSMutableArray arrayWithCapacity:2]; // will grow if needed.

for( some loop conditions )
{
  NSString* someCity = getCity();
  [myCities addObject:someCity];
}

NSLog(@"number of cities in array: %@",[myCities count]);
于 2012-09-11T07:55:43.643 回答