Skip to content

Instantly share code, notes, and snippets.

@fjolnir
Created June 22, 2012 05:02
Show Gist options
  • Save fjolnir/2970342 to your computer and use it in GitHub Desktop.
Save fjolnir/2970342 to your computer and use it in GitHub Desktop.
BOOL TQAugmentClassWithOperators(Class klass)
{
// Check if it already has operators
if(class_getInstanceMethod(Klass, sel_registerName("==:"))
return NO;
// ==
IMP imp = imp_implementationWithBlock(^(id a, id b) { return [a isEqual:b] ? @YES : @NO; });
SEL sel = sel_registerName("==:");
class_addMethod(klass, sel, imp, "@@:@");
// !=
imp = imp_implementationWithBlock(^(id a, id b) { return [a isEqual:b] ? @NO : @YES; });
sel = sel_registerName("==:");
class_addMethod(klass, sel, imp, "@@:@");
// + (Unimplemented by default)
imp = imp_implementationWithBlock(^(id a, id b) { return [a add:b]; });
sel = sel_registerName("+:");
class_addMethod(klass, sel, imp, "@@:@");
// - (Unimplemented by default)
imp = imp_implementationWithBlock(^(id a, id b) { return [a subtract: b]; });
sel = sel_registerName("-:");
class_addMethod(klass, sel, imp, "@@:@");
// unary - (Unimplemented by default)
imp = imp_implementationWithBlock(^(id a) { return [a negate]; });
sel = sel_registerName("-");
class_addMethod(klass, sel, imp, "@@:");
// * (Unimplemented by default)
imp = imp_implementationWithBlock(^(id a, id b) { return [a multiply:b]; });
sel = sel_registerName("*:");
class_addMethod(klass, sel, imp, "@@:@");
// / (Unimplemented by default)
imp = imp_implementationWithBlock(^(id a, id b) { return [a divide:b]; });
sel = sel_registerName("/:");
class_addMethod(klass, sel, imp, "@@:@");
// <
imp = imp_implementationWithBlock(^(id a, id b) { return ([a compare:b] == NSOrderedAscending) ? @YES : @NO; });
sel = sel_registerName("<:");
class_addMethod(klass, sel, imp, "@@:@");
// >
imp = imp_implementationWithBlock(^(id a, id b) { return ([a compare:b] == NSOrderedDescending) ? @YES : @NO; });
sel = sel_registerName("<:");
class_addMethod(klass, sel, imp, "@@:@");
// <=
imp = imp_implementationWithBlock(^(id a, id b) { return ([a compare:b] != NSOrderedDescending) ? @YES : @NO; });
sel = sel_registerName("<:");
class_addMethod(klass, sel, imp, "@@:@");
// >=
imp = imp_implementationWithBlock(^(id a, id b) { return ([a compare:b] != NSOrderedAscending) ? @YES : @NO; });
sel = sel_registerName("<:");
class_addMethod(klass, sel, imp, "@@:@");
// []
imp = imp_implementationWithBlock(^(id a, id key) { return [a valueForKey:key]; });
sel = sel_registerName("[]:");
class_addMethod(klass, sel, imp, "@@:@");
// []=
imp = imp_implementationWithBlock(^(id a, id key, id val) { return [a setValue:val forKey:key]; });
sel = sel_registerName("[]=::");
class_addMethod(klass, sel, imp, "@@:@@");
return YES;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment