Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Categories with the same function name in Objective C [duplicate]

If an 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 output for this :

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

The output I am getting is always

#import "NSData+test1.h"

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

The problem here is that if you are importing two SDK's with static libraries that have categories with the same name, how do you get around the problem. I'm assuming the only way is to ask the SDK creator's to use a prefix for the method names?

like image 769
Mustafa Avatar asked Mar 15 '13 02:03

Mustafa


1 Answers

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

Avoid Category Method Name Clashes

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

If the name of a method declared in a category is the same as a method in the original class, or a method in another category on the same class (or even a superclass), the behavior is undefined as to which method implementation is used at runtime. This is less likely to be an issue if you’re using categories with your own classes, but can cause problems when using categories to add methods to standard Cocoa or Cocoa Touch classes.

like image 166
Perception Avatar answered Nov 15 '22 07:11

Perception