如果两个 ObjC 类别覆盖相同的方法会发生什么? [英] What happens if two ObjC categories override the same method?

查看:20
本文介绍了如果两个 ObjC 类别覆盖相同的方法会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道一些关于 Objective-C 类别的规则:

<块引用>

  1. 类别方法不应覆盖现有方法(类或实例)
  2. 为同一个类实现相同方法的两个不同类别将导致未定义行为

我想知道当我在同一类别中覆盖我自己的类别方法之一时会发生什么.例如:

@interface NSView (MyExtensions)- (void)foo;//NSView 类别实现@结尾@interface MyClass : NSView{ }@结尾@interface MyClass (MyExtensions)- (void)foo;//MyClass 类实现@结尾

定义了这些接口后,运行下面的代码会执行哪个方法?

MyClass * instance = [[MyClass alloc] initWith...];[实例 foo];【实例发布】;

注意:对于我的编译器,MyClass 实现优先,但我不确定这是否一定会发生,或者只是未定义行为的一种特定风格.

解决方案

每个类的每个方法都有一个实现.类别添加或替换特定类的方法.这意味着您所看到的行为是明确定义的,其中 MyClass 有一个 foo 而 NSView 有另一个 foo.MyClass 的任何实例都将具有与任何非 MyClass 的 NSView 实例不同的 foo ,就像 foo 已在主要实现中定义而不是类别一样.您甚至应该能够从 MyClass 调用 [super foo] 来访问为 NSView 定义的 foo.

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

  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];

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.

解决方案

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.

这篇关于如果两个 ObjC 类别覆盖相同的方法会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆