2012-01-11 66 views
13

我想在iPhone中獲取NSMutableDictionary數。我想知道NSMutableDictionry中有多少項。我試過這些代碼來找出解決方案,但沒有幫助我很多。如何在iPhone中獲取NSMutableDictionary計數?

NSLog(@"Count : %d", [mutableDictionary count]); 

總是返回'0'。如何獲得iPhone中的NSMutableDictionary的計數?提前致謝。

回答

30

您可以瞭解有多少的關鍵對象(鍵值)對有像這樣:

NSArray * allKeys = [mutableDictionary allKeys]; 
NSLog(@"Count : %d", [allKeys count]); 

編輯

在通過字典文件看,NSDictionarycount方法(或財產)也應該工作。我想你可能已經收到0次數,因爲字典是空的或無。我提供了我的解決方案,因爲我傾向於更多地關心列舉鍵而不是直接計算條目。

請考慮一下事實,即您在其他地方解決了問題。
•通過實際填充字典

•通過固定的臭蟲mutableDictionary在某種程度上零

我運行這個測試代碼,並獲得評論輸出

NSMutableDictionary * countDict = [NSMutableDictionary dictionaryWithObject:@"test" forKey:@"test"]; 
    [countDict setObject:@"foo" forKey:@"bar"]; 
    NSLog(@"test count %d", countDict.count); //test count 2 
    countDict = nil; 
    NSLog(@"test count %d", countDict.count); //test count 0 
10

[[dictionary allKeys] count];會做的伎倆。

2
 NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"Rakesh",@"Name",@"[email protected]",@"Email",nil]; 
    NSLog(@"Count : %d", [dict count]) 

試試這個

+0

它會返回計數:2 – 2012-01-11 07:09:35

+1

@RakeshBhatt +1從我。在對count方法進行了一些研究之後,我編輯了我的答案。我相信OP已經解決了其他一些問題。 – 2012-01-11 07:32:02

0

,如果你希望計數的NSMutableDictionary值,你可以使用任何數組項。

NSLog(@"myDictionaryCount %lu", (unsigned long)[myDictionary[@"items"] count]); 
相關問題