如何确定在Objective-C中是否覆盖了超类私有方法?

时间:2014-02-27 04:59:25

标签: objective-c cocoa inheritance

因为在Objective-C中,私有方法并不是私有的(方法调度机制不区分私有v / s公共方法),所以子类很容易覆盖超类的私有方法(更多)在Cocoa Coding Guidelines)。

但是,检测到这一点并不容易。我正在寻找一个可以帮助我的现成工具。

这不能简单地成为静态分析工具,因为私有方法不会在界面中公开。该工具要么必须检查二进制文件,要么在运行时计算出来。据我所知,这个工具必须做类似以下的事情:

  1. 通过检查标题获取项目使用的每个类的所有公共方法的列表,然后执行步骤2或步骤3

  2. 通过检查二进制文件获取被重写的私有方法

    a)读取应用程序二进制文件及其链接的所有动态库,以获取应用程序使用的每个类定义的所有方法的列表。

    b)其中,步骤1中未找到的方法是私有方法。

    c)浏览类层次结构并找出覆盖私有超类方法的子类

  3. 在运行时获取重写的私有方法

    a)运行应用程序

    b)使用Objective-C运行时方法,我们可以获得为所有类定义的所有方法。

    c)同样,步骤1中未找到的方法是私有方法

    d)浏览类层次结构并找出重写超类私有方法的子类

  4. 这并不总是有效 - 因为可以在运行时添加/删除类和方法,有些情况会被遗漏(最值得注意的是,NSManagedObject子类,其中在运行时提供了Core Data属性的方法)。不过没关系,我愿意忍受这个限制。

    我相信很有可能使用libclangotoolnm等对象文件检查工具以及Objective-C运行时来实现这一目标,但是有一个现成的工具吗?做这一切吗?

    注意:我不是在寻找减轻这个问题的方法;只是如何检测这种情况。

1 个答案:

答案 0 :(得分:1)

您可以通过点击Objective-C运行时来完成此任务。

参见objc / runtime.h,即:

/** 
 * Describes the instance methods implemented by a class.
 * 
 * @param cls The class you want to inspect.
 * @param outCount On return, contains the length of the returned array. 
 *  If outCount is NULL, the length is not returned.
 * 
 * @return An array of pointers of type Method describing the instance methods 
 *  implemented by the class—any instance methods implemented by superclasses are not included. 
 *  The array contains *outCount pointers followed by a NULL terminator. You must free the array with free().
 * 
 *  If cls implements no instance methods, or cls is Nil, returns NULL and *outCount is 0.
 * 
 * @note To get the class methods of a class, use \c class_copyMethodList(object_getClass(cls), &count).
 * @note To get the implementations of methods that may be implemented by superclasses, 
 *  use \c class_getInstanceMethod or \c class_getClassMethod.
 */
OBJC_EXPORT Method *class_copyMethodList(Class cls, unsigned int *outCount) 
     __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0);
相关问题