开发者

iPhone how to get a running tally of unique items in an Array?

开发者 https://www.devze.com 2023-02-28 13:55 出处:网络
Lets say I have an NSArray full of animal objects and their names are string attributes. As I iterate through the array, how would I get a running tally of similar names?

Lets say I have an NSArray full of animal objects and their names are string attributes. As I iterate through the array, how would I get a running tally of similar names?

Cat - Bob count:1

开发者_开发问答

Dog - Sally count:1

Cat - Bob count:2

Bunny - Bob count:3

Fish - Sally count:2

How would I get these ints if the names are dynamic, not static?


The most straightforward way would be to use an NSMutableDictionary. For each name, try to fetch the NSNumber for that name from the dictionary. If one was found, add 1 and store it back; if not, create a new one with the value 1 and store it.


I guess you could use a NSMutableDictionary in order to hold a count of the names.

Something like:

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

The line "NSNumber *number = (NSNumber *)[dic objectForKey:name]" retrieves the number of times a specific name appeared.

You can also use [dic allKeys]; to retrieve all the names in that dictionary.

0

精彩评论

暂无评论...
验证码 换一张
取 消