将一个数组的元素值加载到另一个数组Xcode Objective-C



这里我从tgpList1数组中获取城市名称为Piscataway、Iselin、Broklyn等的cityName1,我需要将这些值放入一个名为item5的数组中。

通过上述迭代提取了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];
}

使用可变数组。

{
   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];
   }
}

而不是

item5 =[NSArray arrayWithObjects:cityName1, nil];

使用

[item5 addObject:cityName1];

实现这一目标的方法还有很多。然而,这是为这个目的而设计的,也是我认为最"可读"的。

如果您需要在之前清除项目5的内容,请致电

[item5 removeAllObjects]; 

就在for循环之前。

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

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]);

最新更新