2011-04-23 43 views
0

可以說我有一個NSArray充滿了動物對象,它們的名字是字符串屬性。 當我遍歷數組時,我將如何獲得類似名稱的運行記錄?iPhone如何獲得陣列中獨特項目的運行計數?

貓 - 鮑勃計數:1

狗 - 薩利計數:1個

貓 - 鮑勃數:2

兔子 - 鮑勃數:3

魚 - 薩利數:2

如果名稱是動態的,而不是靜態的,我將如何得到這些整數?

+0

什麼是動物類(和子類)的申報? – 2011-04-24 00:01:06

回答

1

最直接的方法是使用NSMutableDictionary。對於每個名稱,嘗試從字典中獲取該名稱的NSNumber。如果找到一個,請加1並將其存回;如果沒有,則創建一個值爲1的新值並將其存儲。

0

我想你可以爲了保持名稱的計數使用的NSMutableDictionary。

是這樣的:

NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithCapacity:10]; 

NSString *name = [NSString stringWithFormat:@"Bob"];  
NSNumber *number = (NSNumber *)[dic objectForKey:name]; 

if (number == nil) // There is no occurrence of the name in Dictionary 
{ 
    number = [NSNumber numberWithInt:1]; 
    [dic setObject:number forKey:name]; 
} 
else // There is already an occurrence of the name in dictionary, so increment counter 
{ 
    number = [NSNumber numberWithInt:(number.intValue + 1)]; // Increments counter for Name 
    [dic objectForKey:name]; 
} 

線 「的NSNumber *號=(的NSNumber *)[DIC objectForKey:名稱]」 檢索的次特定的名稱出現的數目。

您也可以使用[DIC allKeys]檢索該字典中的所有名稱。