计算字典中的所有项目

时间:2010-02-21 11:30:07

标签: iphone objective-c dictionary count

我的问题是: 我有一个字典,每个字符的字符都有一个对象。在这些对象中,存在特定字符的所有值。

示例:

alphabetDictionary
  a
    apple
    alien
  b 
   balloon
   ball

我现在想要计算这本词典中的所有条目:

apple
alien
balloon
ball
-> 4

使用此源代码只计算对象(a,b等)

NSString *counter = [NSString stringWithFormat:@"Entries (%d)", alphabetDictionary.count];

那么如何获取所有条目而不是对象a,b等?

编辑1: 在viewDidLoad方法中我有:

//Initialize the array.
charDict = [[NSMutableDictionary alloc] init];
alphabetArray = [[NSMutableArray alloc] init];

if ([charSpecialArray count] > 0)   {

    //Set object for this character within the dictionary
    [charDict setObject:charSpecialArray forKey:@"#"];
    //fill the alphabetArray with an index value, if this char exists at all
    [alphabetArray addObject:@"#"];
}

if ([charAArray count] > 0) {

    [charDict setObject:charAArray forKey:@"A"];
    [alphabetArray addObject:@"A"];
}
每个角色

等..

接下来是:

totalCounter = 0;
//Count all keys within the Dictionary
for (id objectKey in charDict.allKeys) {
    totalCounter += [[charDict objectForKey:objectKey] count];
    NSLog(@"Anzahl: %d", totalCounter);
}   
NSString *counter = [NSString stringWithFormat:@"TXNs (%d)", totalCounter];

self.title = counter;

结果看起来太高了:

  • 字符H有33个条目
  • H字符的计数结果为:132
  • m字符:1587
  • m个字符数:6348

为什么那些重要的想法很高?

6 个答案:

答案 0 :(得分:3)

a,b等是关键。数组[apple,alien]等是对象。

要获得总计数,您需要遍历字典并总结:

NSUInteger total = 0;
for (NSString* key in alphabetDictionary) {
  total += [[alphabetDictionary objectForKey:key] count];
}
return total;

或者使用这种非常慢的单线:

int count = [[[d allValues] valueForKeyPath:"@sum.@count"] intValue];

答案 1 :(得分:1)

NSEnumerator *aEnum = [alphabetDictionary objectEnumerator];
id object;
NSUInteger count = 0;
while( object = [aEnum nextObject] ){
 count += [object count]; // assuming that the object is an array
}
NSString *countStr = [NSString stringWithFormat:@"Entries (%ld)",count];
// %d NO ofcourse not its not a NSInteger we want a Long

答案 2 :(得分:0)

使用fast enumeration

NSUInteger count = 0; 
for (id objectKey in alphabetDictionary.allKeys) {
    count += [alphabetDictionary objectForKey:objectKey].count;
}
NSString *countStr = [NSString stringWithFormat:@"Entries (%ud)", count];

答案 3 :(得分:0)

由于投票和所有答案,我无法删除此问题。 所以这里是我自己的答案,为什么计数条目的数量如此之高:

如果NSUInteger

,我使用的是NSInteger

答案 4 :(得分:0)

我的问题的解决方案是: 我用过NSInteger而不是NSUInteger

答案 5 :(得分:0)

我必须在Swift中做同样的事情。我有一个Dictionary arrays。导致以下代码:

var totalItemsOfAllPages:Int {
    var totalItemsCount = 0

    loadedPages.values.array.map({
        totalItemsCount += $0.count
    })

    return totalItemsCount
}
相关问题