• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: counting objects in array
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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.


  • Follow-Ups:
    • Re: counting objects in array
      • From: Prachi Gauriar <email@hidden>
References: 
 >counting objects in array (From: Koen van der Drift <email@hidden>)

  • Prev by Date: Re: Plug Ins - To Subclass or to Protocol?
  • Next by Date: Detecting Changes in NSObjectController
  • Previous by thread: counting objects in array
  • Next by thread: Re: counting objects in array
  • Index(es):
    • Date
    • Thread