Wednesday, January 19, 2011

NSCountedSet

I just got a helpful comment on an old post (here) suggesting the use of an NSCountedSet. I'd never heard of this class, but it's described in the Apple docs about Collections (here). Besides the usual characters

NSArray
NSMutableArray
NSDictionary
NSMutableDictionary
NSIndexSet

there are several others including:

NSPointerArray
NSPointerFunctions
NSMapTable
NSHashTable
NSCountedSet

Let's show off the last one, from PyObjC. Here's the listing:

from Foundation import *

L = list('xyyzzz')
S = NSCountedSet.alloc().initWithArray_(L)

def show(S):
e = S.objectEnumerator()
while True:
obj = e.nextObject()
if not obj: break
print obj, S.countForObject_(obj)
print

show(S)
N = S.countForObject_('z')
for i in range(N):
S.removeObject_('z')
print 'z', S.countForObject_('z')
print 'w', S.countForObject_('w')

and the output:

x 1
y 2
z 3

z 2
z 1
z 0
w 0

It feels a bit strange, not only can you get the count of an object that's not in the set (as in Python), but as the docs say:
removeObject: does nothing if anObject is not present in the set