Search code examples
objective-ccore-datamagic-methods

How to create magic methods in Objective C


I am trying to develop a set of magic findByX methods in a generic Model class that eventually will issue queries to Core Data using NSPredicate objects:

  • (id)findByName;
  • (id)findByCreated;
  • ...

Following advice from a previous SO question I can intercept messages that request non-existent methods by overriding resolveInstanceMethod:

#include <objc/runtime.h>

+ (BOOL) resolveInstanceMethod:(SEL)aSel {
  if (aSel == @selector(resolveThisMethodDynamically)) {
    class_addMethod([self class], aSel, (IMP) dynamicMethodIMP, "v@:");
    return YES;
  }
  return [super resolveInstanceMethod:aSel];
}

void dynamicMethodIMP(id self, SEL _cmd) {
  NSLog(@"Voilà");
}

However, when I try to use [myObject resolveThisMethodDynamically] the compiler raises the following error:

"No visible @interface for 'MyModel' declares the selector 'resolveThisMethodDynamically'"

which makes sense, since there isn't any declaration of that method. So, what am I missing here? Is there any best practice to accomplish this?

Thank you!


Solution

  • I'm not sure if it's exactly what you're after, but here are a couple of helpful resources for this sort of Core Data functionality:

    MagicalRecord is a small framework for Core Data that makes it work a lot like ActiveRecord from the Ruby world. In particular, it implements a lot of the fetching functionality you're after, I think. Check out the categories it adds to NSManagedObject.

    Hope this helps!