Andres C. Viesca
Andres C. Viesca

Reputation: 342

dynamically add a method to the app delegate

Say I have this instance method [1]:

    -(BOOL)application:(UIApplication *)application
               openURL:(NSURL *)url {

      NSLog(@"url --> %@", url); 
      //Do something...
      return YES;
    }

And if I am not mistaken, [[UIApplication sharedApplication] delegate] [2] is the instance of my app delegate.

I want to dynamically add my instance method [1] to the app delegate [2] from any other class.

I have found that class_addMethod *info might help me, but it mentions nothing about how to specify if its an instance method or a class method.

Edit:

Following @mipadi 's advice bellow, I am trying to call

class_addMethod([AppDelegate class], @selector(newMethod), (IMP)myMethodIMP, "v@:");

but I get the following errors:

And the following warning:

I am really not sure what is wrong and this errors make little sense to me.

Upvotes: 0

Views: 268

Answers (1)

mipadi
mipadi

Reputation: 410562

class_addMethod always adds an instance method to a class. To add a class method, you would add the method to your class's meta-class.

Let's say your delegate class is called MyDelegate. Obviously you can create instances of MyDelegate. For example, in id obj = [[MyDelegate alloc] init], obj is an instance of MyDelegate. However, the MyDelegate class itself is an instance of its meta-class. It is this meta-class to which you add MyDelegate's class methods, because MyDelegate's class methods are actually instance methods defined on its meta-class.

So, to add an instance method, you'd do something like this:

class_addMethod([MyDelegate class], @selector(newMethod), (IMP) newMethodImpl, newMethodTypeSig);

To add a class method, you'd do the same with MyDelegate's meta-class as the first argument, which you can get using object_getClass:

class_addMethod(object_getClass([MyDelegate class]), @selector(newClassMethod), (IMP) newClassMethodImpl, newClassMethodTypeSig);

(Note that somewhat confusingly, [myDelegateInstance class] and [MyDelegate class] actually return identical objects; that is, +[MyDelegate class] returns itself. [MyDelegate class] does not return MyDelegate's meta-class, as you may expect.)

Upvotes: 1

Related Questions