Skip to content

Instantly share code, notes, and snippets.

@bofh
Created November 19, 2011 18:12
Show Gist options
  • Save bofh/1379150 to your computer and use it in GitHub Desktop.
Save bofh/1379150 to your computer and use it in GitHub Desktop.
Syntax sugar idea for collections in ObjC 2.0
/*
* Syntax sugar for collections
* [overlap :@"key"].integer = 0;
*
* gcc -framework Foundation collections.m
*
*/
#import <Foundation/Foundation.h>
@interface Hash : NSObject {
NSMutableDictionary *dict;
}
+ (Hash *)forKey:(id)k target:(Hash *)target;
- (Hash *):(id)key;
@property (readwrite) int integer;
@property (readwrite, assign) Hash *target;
@property (readwrite, assign) id key;
@end
@implementation Hash
@synthesize integer;
@synthesize key;
@synthesize target;
- (id)init
{
if ((self = [super init])) {
dict = [[NSMutableDictionary alloc] init];
}
return self;
}
- (void)setValue:(id)v forKey:(id)k
{
[dict setValue:v forKey:k];
}
- (void)dealloc
{
[dict release];
return [super dealloc];
}
- (NSString *)description
{
return [dict description];
}
+ (Hash *)forKey:(id)k target:(Hash *)target
{
Hash *tmp = [Hash new];
tmp.key = k;
tmp.target = target;
return [tmp autorelease];
}
- (void)setInteger:(int)i
{
[target setValue:[NSNumber numberWithInteger:i] forKey:key];
}
- (Hash *):(id)k
{
return [Hash forKey:k target:self];
}
@end
int main(void)
{
Hash *overlap = [Hash new];
[overlap :@"key1"].integer = 1;
[overlap :@"key2"].integer = 2;
NSLog(@"%@", overlap);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment