2012-09-11 68 views
-1

這裏我得到cityName1與城市名稱像Piscataway,Iselin,Broklyn等取自tgpList1數組,我需要把值放入一個數組調用item5加載一個數組的元素值到另一個數組Xcode Objective-C

有上述迭代獲取的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]; 
} 
+0

格式化你的問題以及鼓勵更好,更快的答案。我這次編輯過你的問題,但請考慮下次格式化問題。 –

+0

嗨,詹姆斯,感謝你的提示,將會遵循它。 – user1583893

回答

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

    } 
} 
+0

Hey Neo,NSArray向NSMutableArray的一個小改動就是這樣做的。非常感謝。感謝所有來自stackoverflow的支持。乾杯!! – user1583893

0

而不是

item5 =[NSArray arrayWithObjects:cityName1, nil]; 

使用

[item5 addObject:cityName1]; 

有實現這一目標的多種方式。然而,這是爲了這個目的而設計的,也是從我的觀點來看最「可讀」的。

如果你需要先清除ITEM5的內容,然後調用

[item5 removeAllObjects]; 

前右側的for循環。

你在做什麼:arrayWithObjects allways創建一個新的數組,它由作爲參考傳遞給它的對象組成。如果你不使用ARC,那麼你會用你的代碼創建一些嚴重的內存泄漏,因爲arrayWithObjects在每個循環中創建並保留一個對象,並且在下一個循環中,剛剛創建的所有對該數組對象的引用都會丟失而不被釋放。如果你做ARC,那麼在這種情況下你不必擔心。

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]); 
相關問題