Search code examples
iosobjective-clinker

No Warning for conflicting category methods


I am running XCode 4.6.3 and try to create a project with a conflicting category methods like below.

//NSString+category1.h
@interface NSString (category1)

-(NSString*)foo;

@end

//NSString+category1.m
#import "NSString+category1.h"

@implementation NSString (category1)

-(NSString*)foo{
    return self;
}

@end


// NSString+category2.h
@interface NSString (category2)

-(NSString*)foo;

@end

//NSString+category2.m
#import "NSString+category2.h"

@implementation NSString (category2)

-(NSString*)foo{
    return self;
}

@end

XCode 4.6 is supposed to give me some warning, however, it is not. Is there a special compiler/linker flag needed to be set?


Solution

  • According to Avoid Category Method Name Clashes in the Programming with Objective-C guide:

    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. ...

    ... In order to avoid undefined behavior, it’s best practice to add a prefix to method names in categories on framework classes, just like you should add a prefix to the names of your own classes. You might choose to use the same three letters you use for your class prefixes, but lowercase to follow the usual convention for method names, then an underscore, before the rest of the method name.

    Bottom line, I believe the burden rests upon the developer to ensure that method names are unique.