0

Possible Duplicate:
What happens if two ObjC categories override the same method?

I have two Categories on NSString class as follows:

//first category

#import "NSString+MyCategory1.h"

@implementation NSString (MyCategory1)

-(void)myMethod{
    NSLog(@"this is my method from category 1");
}

@end

//second category

#import "NSString+MyCategory2.h"

@implementation NSString (MyCategory2)

-(void)myMethod{
    NSLog(@"this is my method from category 2");
}

@end

But the following main method is always calling myMethod from MyCategory1 even after import of the same has been commented out.

#import <Foundation/Foundation.h>
//#import "NSString+MyCategory1.h"
#import "NSString+MyCategory2.h"

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        [[[NSString alloc]init] myMethod];

    }
    return 0;
}

Please anyone explain this behavior and how this behavior is useful in practice.

4

1 回答 1

4

I think what this shows is that you should not have methods in categories that clash.

My (semi informed) guess is that which method gets called us down to how the app was compiled, so it's not something you can influence at runtime. And it's not really useful in practice, it's just... what happens.

As for why this happens, the header file doesn't say what to do when the method is called, only that an implementation for it exists. In your case, it does exist. It just happens not to be the one you want.

于 2012-11-08T13:24:03.213 回答