0

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!

Community
  • 1
  • 1
elitalon
  • 9,191
  • 10
  • 50
  • 86
  • This is a XY problem. See RestKit for how to implement findAll features. Specifically, NSManagedObject+ActiveRecord category. – Paul de Lange Aug 28 '12 at 09:40

3 Answers3

1

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!

James Frost
  • 6,960
  • 1
  • 33
  • 42
0

This got me pretty curious, so I searched around and there are a number of options. This thread sums them up. Personally, I'm sympathetic to the argument that if you add a method at run-time, you should not be choosing the selectors at compile time, but do so at runtime as well. So, use NSSelectorFromString and so on, with some various preprocessor directives to suppress warnings in such cases.

Hope this helps!

Community
  • 1
  • 1
Carl Veazey
  • 18,392
  • 8
  • 66
  • 81
-1

Use

objc_msgSend( myObject, sel_getUid("yourMethod"), param1, param2...);

don't forget to import 'objc/message.h'

Luc-Olivier
  • 3,715
  • 2
  • 29
  • 29