If two different Categories having same method, then which one will be invoked by Objective C runtime system?
If two different Categories having same method, then which one 开发者_JAVA百科will be invoked by objective C runtime system ??
for example:
@interface ClassA (MathOps)
-(void)CategoryMethod;
@end
@interface ClassA (MathOps1)
-(void)CategoryMethod;
@end
@implementation ClassA(MathOps1)
- (void) CategoryMethod{
NSLog(@"Inside Category Method 2");
}
@end
@implementation ClassA(MathOps)
- (void) CategoryMethod{
NSLog(@"Inside Category Method 1");
}
@end
Now if i am calling, [ObjClassA CategoryMethod];, Then which one called ? Why ?
It's undefined. It depends on which category gets loaded first by the runtime, are there's no documented order in which that happens.
Bottom line: don't do this. :)
As @Dave DeLong states, the behavior is undefined. One of the methods will "win", and there's just no way to know which one. If any other code depends on the loosing method, you'll find yourself debugging some potentially weird errors. Best to avoid the situation all together. This is a particular problem when implementing "obvious" helper methods. If those methods get added in a future framework version, your category will either override the new method in the class (if it's in the main class body) or may override the method if its added in a category. Eek.
Many Cocoa frameworks that provide categories for existing (e.g. Cocoa) classes follow a pattern whereby they prepend their class prefix to the method in order to minimize the chance of name collision. So, for example, you would create categories like:
@interface NSObject (MyCategory)
- (void)myprefix_categoryMethod;
@end
精彩评论