如果两个ObjC类别覆盖相同的方法会发生什么?

如果两个ObjC类别覆盖相同的方法会发生什么?

问题描述:

我知道有几个关于Objective-C类别的规则:

I know of a couple of rules regarding Objective-C categories:



  1. 类别方法不应覆写现有方法(类或实例)

  2. 对同一类实现相同方法的两个不同类别将导致未定义的行为

  1. Category methods should not override existing methods (class or instance)
  2. Two different categories implementing the same method for the same class will result in undefined behavior


我想知道当我在同一类别中重写我自己的类别方法时会发生什么。例如:

I would like to know what happens when I override one of my own category methods in the same category. For example:

@interface NSView (MyExtensions)
- (void)foo; // NSView category implementation
@end

@interface MyClass : NSView
{ }
@end

@interface MyClass (MyExtensions)
- (void)foo; // MyClass category implementation
@end

定义这些接口,当我运行下面的代码?

With these interfaces defined, which method will be executed when I run the following code?

MyClass * instance = [[MyClass alloc] initWith...];
[instance foo];
[instance release];

注意:使用我的编译器,MyClass实现优先,但我不知道保证发生,或者只是一种未定义行为的特定风味。

Note: With my compiler, the MyClass implementation takes precedence, but I'm not sure if that is guaranteed to occur, or simply one specific flavor of undefined behavior.

每个类的每个方法都有一个实现。类别添加或替换特定类的方法。这意味着你看到的行为,其中MyClass有一个 foo 和NSView有另一个 foo ,是明确定义的。任何MyClass实例都会有一个不同的 foo 比任何不是M​​yClass的NSView实例,就像 foo 已在主要实施中定义,而不是一个类别。你甚至应该能够从MyClass调用 [super foo] 来访问为NSView定义的 foo

Each method of each class has an implementation. A category adds or replaces a method for a specific class. That means the behavior you are seeing, where MyClass has one foo and NSView has another foo, is well defined. Any instance of MyClass will have a different foo than any instance of NSView that is not a MyClass, just as if foo had been defined in the main implementation and not a category. You should even be able to call [super foo] from MyClass to access the foo defined for NSView.