Categories with the same function name in Objective-C

If the Xcode project has two categories:

@implementation NSData (test1) - (void) testData { NSLog(@"test data 1"); } @end 

and

 @implementation NSData (test2) - (void) testData { NSLog(@"test data 2"); } @end 

What is the expected result for this:

 NSData* testData = [[NSData alloc] init]; [testData testData]; 

The output I get is always

 #import "NSData+test1.h" 

Any explanation on this? Is there a way to force the first category?

The problem is that if you import two SDKs with static libraries that have categories with the same name, how do you deal with the problem. I guess the only way is to ask the SDK creator to use a prefix for the method names?

+4
source share
1 answer

The behavior is undefined and should be avoided. Here is the relevant documentation :

Avoid categorical method name

Since methods declared in a category are added to an existing class, you must be very careful about method names.

If the name of a method declared in a category matches the name of a method in the source class or a method in another category on the same class (or even a superclass), the undefined behavior regarding which method is used at runtime . This is less likely if you use categories with your own classes, but you might have trouble using categories to add methods to the standard Cocoa or Cocoa Touch classes.

+13
source

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


All Articles