5

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?

Kara
  • 6,115
  • 16
  • 50
  • 57
Mustafa
  • 5,307
  • 1
  • 20
  • 19

1 Answers1

16

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.

Community
  • 1
  • 1
Perception
  • 79,279
  • 19
  • 185
  • 195
  • 1
    What exactly is meant by undefined behavior. What if my purpose is exactly that, to use a category to override the existing behavior of the class method? – RobDigital Jul 16 '15 at 17:00