Objective-C Method Name Alias

I have a fairly simple question that I cannot find a definitive answer to.

Is there a way to make an alias for a method without by doing something like this:

- (void)method1 { //Stuff } - (void)method2 { [self method1];} 

I want [self method2]; equated to [self method1]; creating an alias. Is this possible in Objective-C?

+4
source share
2 answers

If you're looking for a way to do this without writing a lot of code, you're out of luck. As a rule, Obj-C does not have much "syntactic sugar", and this is one such situation.

In most cases, you just do exactly what you are trying to avoid. It is easy and works.

But when it’s not very good, the Obj-C runtime has the “Forward Messages” feature.

Basically, if your object receives a message (method call) that it knows nothing about, the default behavior is to throw an exception. But your object may decide to do something else with it, and there are millions of places where the Obj-C Framework classes do this.

In most cases, you forward the message to another object, but you can do whatever you want:

 - (void)forwardInvocation:(NSInvocation *)anInvocation { if (/* some check */) { /* do something */ return; } // perform the superclass implementation (which is probably to throw a "method not recognized" exception. [super forwardInvocation:anInvocation]; } 

The official documentation with many details can be found here: https://developer.apple.com/library/ios/DOCUMENTATION/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtForwarding.html

+3
source

If you are using a dynamic solution, you can use objc runtime for this. class_addMethod is an API that will do this for you.

class_addMethod will not replace, but other APIs may - Be careful not to replace existing implementations. A good prefix for your selector name would be a good idea so that you can avoid collisions.

0
source

Source: https://habr.com/ru/post/1499981/


All Articles