Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C and magic methods in class

Does objective-c offer a way to intercept calls to class method that does not exist?

like image 385
mgamer Avatar asked Aug 04 '11 09:08

mgamer


People also ask

What are magic methods?

Magic methods are special methods which override PHP's default's action when certain actions are performed on an object. All methods names starting with __ are reserved by PHP. Therefore, it is not recommended to use such method names unless overriding PHP's behavior.

Is __ init __ a magic method?

These are commonly used for operator overloading. Few examples for magic methods are: __init__, __add__, __len__, __repr__ etc.

What is the purpose of the magic method?

Magic methods are special methods in python that have double underscores (dunder) on both sides of the method name. Magic methods are predominantly used for operator overloading.


2 Answers

The forwardInvocation method is what you are going to want to use. It is called automatically when a non-existent selector is called on an object. The default behavior of this method is to call doesNotRecognizeSelector:(which is what outputs debug information to your console), but you can override it do anything you want. One recommended approach by Apple is to have this method forward the method invocation to another object.

- (void)forwardInvocation:(NSInvocation *)anInvocation

Note that forwardInvocation is a fairly expensive operation. An NSInvocation object needs to be created by the framework and (optionally) used to invoke a selector on another instance. If you are looking for a (relatively) faster method of detecting non-existent selectors then you can choose to implement forwardingTargetForSelector instead.

- (id)forwardingTargetForSelector:(SEL)aSelector

You should Apple's documentation for how to override these methods effectively, there are some gotcha's to watch out for, particularly when overriding the forwardInvocation method on the same object that will have the missing selectors.

like image 172
Perception Avatar answered Oct 15 '22 04:10

Perception


Yes, you can with the resolveClassMethod: class method (which is defined on NSObject):

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html

Here is also something to watch out for (stumped me the first time): http://iphonedevelopment.blogspot.com/2008/08/dynamically-adding-class-objects.html

like image 28
dtuckernet Avatar answered Oct 15 '22 04:10

dtuckernet