2010-09-21 108 views
1
counter = [myArray count]; 
for (i = 0 ; i < count ; i++) { 
    [[anotherArray objectAtIndex:i] setTitle:[myArray objectAtIndex:i]]; 
} 

我想做它的目標C 2.0的方式,但似乎無法找到如何訪問索引'我'(如果這是可能的反正)。for循環Objective-C

for (NSString *myString in myArray) { 
    [[anotherArray objectAtIndex:i] setTitle: myString]; 
} 

(請原諒任何的拼寫錯誤,我目前還沒有我的Mac落後,所以這是從我的頭。)

回答

6

要做到這一點,你必須跟蹤指數自己:

NSUInteger index = 0; 
for (NSString *myString in myArray) { 
    [[anotherArray objectAtIndex: index] setTitle: myString]; 
    ++index; 
} 

也許在這種情況下,一個老式的for與索引循環是更好的選擇。除非你在這裏嘗試使用快速枚舉出於性能原因。

但重構代碼可能會更好,因此您不必將myArray中的字符串手動複製到anotherArray中對象的標題屬性。

+0

我同意但我不知道如何。讓我解釋一下:字符串用於本地化。從包中讀取一個數組,並將這些字符串分配給tabBar中的tabBarItems的標題屬性。 (我更喜歡不製作本地化的xib文件,因爲每次添加控件都會產生大量額外的工作>連接IBOutlets + IBActions,因此我採用了本地化plists的路徑......) – Glenn 2010-09-21 21:05:19

+0

我明白了。您可能想查看'NSLocalizedStringFromTable'和字符串文件,而不是在屬性列表上構建自己的本地化函數。你也可以試試這個:http://wilshipley.com/blog/2009/10/pimp-my-code-part-17-lost-in.html – Sven 2010-09-22 00:03:47

5

使用塊。

[myArray enumerateObjectsUsingBlock ^(id obj, NSUInteger idx, BOOL *stop) { 
     [[anotherArray objectAtIndex: idx] setTitle: obj]; 
}];