Override a method in Objective c via category

后端 未结 3 1201
滥情空心
滥情空心 2020-12-08 21:21

The following is working in objective c:

// Base Class in ClassA.h and ClassA.m
@interface ClassA : NSObject 
- (NSString *) myMethod;
@end
@implementation C         


        
3条回答
  •  借酒劲吻你
    2020-12-08 21:33

    Objective-C messaging is dynamic, this means that it doesn't matter if you import or not the category. The object will receive the message and execute that method.

    The category is overriding your method. This means that when the runtime sends a message to that object, will always find the overridden method, no matter what you import.

    If you want to ignore a category you shouldn't compile it, so you could remove the category from the compiler sources.
    An alternative is subclassing.

    Also read this:

    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.

    So in your case you haven't got any problem because as stated, this is less likely to happen with user defined classes. But you should definitely use subclassing instead of writing a category.

提交回复
热议问题