使用具有相同方法名称的类别扩展类 [英] Extending a class using categories with identical methods name

查看:56
本文介绍了使用具有相同方法名称的类别扩展类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 NSArray + Populate.h 类扩展一个类:

I want to extend a class using category NSArray+Populate.h:

@interface NSArray (Populate)
-(NSArray *) populateArray; 
@end

如果有其他类别(来自另一个模块),如何检测情况或库),使用同名方法扩展NSArray?

How can I detect the situation if there is another category (from another module or library), extending NSArray with method having the same name ?

例如,如果有 NSArray + Fill.h

@interface NSArray (Fill)
-(NSArray *) populateArray; 
@end

据我所知,运行时引擎会选择其中一个版本默默地,没有任何崩溃?

As I understand, the run-time engine will choose one of the version silently, without any crash ?

推荐答案

你无法检测到这种情况,你无法确定的哪个实现 - populateArray 优先。由于这个原因,一些开发人员更喜欢为他们的类别方法名称添加前缀。

You cannot detect this situation and you cannot determine which implementation of -populateArray takes precedence. Some developers prefer to prefix their category method names for this reason.

引用 Objective-C编程语言文档,


类别不能可靠地覆盖在同一类的另一个类别中声明的方法。

A category cannot reliably override methods declared in another category of the same class.

这个问题特别重要,因为许多Cocoa类是使用类别实现的。您尝试覆盖的框架定义方法本身可能已在类别中实现,因此未定义优先级实现。

This issue is of particular significance since many of the Cocoa classes are implemented using categories. A framework-defined method you try to override may itself have been implemented in a category, and so which implementation takes precedence is not defined.

这篇关于使用具有相同方法名称的类别扩展类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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