Skip to content

Instantly share code, notes, and snippets.

@jparise
Created January 31, 2012 19:44
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jparise/1712497 to your computer and use it in GitHub Desktop.
Save jparise/1712497 to your computer and use it in GitHub Desktop.
NSCountedSet(NSDictionaryExtensions)
#import <Foundation/Foundation.h>
@interface NSCountedSet (NSDictionaryExtensions)
- (id)initWithDictionary:(NSDictionary *)dict;
- (void)addObjectsFromDictionary:(NSDictionary *)dict;
- (NSDictionary *)dictionary;
@end
#import "NSCountedSet+Dictionary.h"
@implementation NSCountedSet (NSDictionaryExtensions)
- (id)initWithDictionary:(NSDictionary *)dict
{
if ((self = [super initWithCapacity:[dict count]]))
{
[self addObjectsFromDictionary:dict];
}
return self;
}
- (void)addObjectsFromDictionary:(NSDictionary *)dict
{
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop){
NSUInteger count = [obj unsignedIntegerValue];
for (NSUInteger i = 0; i < count; ++i)
{
[self addObject:key];
}
}];
}
- (NSDictionary *)dictionary
{
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:self.count];
for (id object in self)
{
NSUInteger count = [self countForObject:object];
[dict setObject:[NSNumber numberWithUnsignedInteger:count] forKey:object];
}
return dict;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment