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

将数组的元素值加载到另一个数组Xcode Objective-C,objective-c,xcode,arrays,Objective C,Xcode,Arrays,这里,我从tgpList1数组中获取cityName1,其中包含城市名称,如皮斯卡塔韦、伊塞林、布罗克林等,我需要将这些值放入名为item5的数组中 通过上述迭代获取了133条记录。下面的代码仅存储最后一条记录的cityName1,而不是循环中的整个城市名称列表 我尝试了很多方法,但是我错过了一些东西 tgpList1是一个数组。 tgpDAO是一个NSObject,包含两个对象NSString*airportCode和NSString*cityName NSArray *item5 = [[N

这里,我从
tgpList1
数组中获取
cityName1
,其中包含城市名称,如皮斯卡塔韦、伊塞林、布罗克林等,我需要将这些值放入名为
item5
的数组中

通过上述迭代获取了133条记录。下面的代码仅存储最后一条记录的
cityName1
,而不是循环中的整个城市名称列表

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

tgpList1
是一个数组。
tgpDAO
是一个NSObject,包含两个对象
NSString*airportCode
NSString*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];
}
NSArray*item5=[[NSArray alloc]init];
对于(int currentIndex=0;currentIndex而不是

item5 =[NSArray arrayWithObjects:cityName1, nil];
使用

实现这一目标的方法还有很多,然而,从我的观点来看,这是一个为实现这一目标而设计的方法,也是最“可读”的方法

如果您需要先清除第5项的内容,请致电

[item5 removeAllObjects]; 
就在for循环之前

您所做的:arrayWithObjects始终创建一个新数组,该数组由作为AGUMENT传递给它的对象组成。如果不使用ARC,则会在代码中造成严重的内存泄漏,因为arrayWithObjects在每个循环和下一个循环中创建并保留一个对象,所有对array对象的引用都是如此是刚创建的,没有发布就丢失了。如果您这样做了,那么您就不必担心这种情况。

使用可变数组

{

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

   }
}
{
NSMutableArray*item5=[[NSMutableArray alloc]initWithArray:nil];

对于(In CurrurtCurdie= 0;您的问题的当前索引将鼓励更好、更快的回答。这次我已经编辑了您的问题,但是请考虑下一次类似的格式化问题。嗨,杰姆斯,谢谢您的笔记,将跟随它。Hey Neo,伟大的只是NSRAPE的一个小小的改变,NSMutableArray做了这个把戏。非常感谢。.谢谢stackoverflow的支持。干杯!!
{

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

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