Re: counting objects in array
Re: counting objects in array
- Subject: Re: counting objects in array
- From: Jonathan Jackel <email@hidden>
- Date: Tue, 20 Jul 2004 19:08:07 -0400
On Jul 19, 2004, at 9:10 PM, Koen van der Drift wrote:
Hi,
I came up with the following code to count the occurences of objects
in an array. In this snippet I count the names of the persons in an
array (how many Micks, Keiths, Charlies, etc) It works, but I was
wondering if this is a 'good' approach.
This was written in, but I think it's right.
You can scrunch it a bit with some modest C tricks and avoiding the
repetitive calls to -allKeys:
- (NSDictionary *)namesAndCountsForPersons:(NSArray *)persons
{
NSMutableDictionary *tempDict = [NSMutableDictionary dictionary];
Person *person;
NSString *aName;
NSEnumerator *ePersons = [persons objectEnumerator];
int count = 0;
while (person = [ePersons nextObject])
{
aName = [person name];
if(!(count = [[tempDict objectForKey:aName] intValue] + 1))
{
count = 1;
}
[tempDict setObject:[NSNumber numberWithInt:count] forKey:aName];
}
return tempDict;
}
If tempDict does not have the name in it already, the if() will resolve
to nil and count will be set to 1. Otherwise, count is set to the
previous count plus 1.
Jonathan
while (person = [enumerator nextObject])
{
aName = [person name];
if ( nil == [[tempDict allKeys] containsObject: aName] ) {
// first occurance
count = [NSNumber numberWithInt:1];
}
else
{
count = [NSNumber numberWithInt: ([[tempDict objectForKey: aName]
intValue] + 1)];
}
[tempDict setObject: count forKey: aName];
}
thanks,
- Koen.
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.