【问题标题】:How can I view the contents of an objective C Protocol?如何查看目标 C 协议的内容?
【发布时间】:2015-11-18 07:12:05
【问题描述】:

如果我可以访问一个 Objective-C 协议并试图弄清楚如何查看它的内部以查看它包含哪些方法,包括它们的签名等。

我尝试过 NSLog 并在调试器中以及在 Internet 上查看对象,但找不到任何方法。

【问题讨论】:

  • 看一下定义协议的.h文件? “有权访问”是什么意思?
  • 协议不“包含”任何方法。它仅定义了必须由采用(符合)协议的人实现的方法的要求。

标签: ios objective-c debugging protocols


【解决方案1】:

在看到这个 SO 帖子的答案后,我检查了 objc/runtime.h 中的方法:List selectors for Objective-C object 并找到了 NSLog 协议的方法签名的方法

#import <objc/runtime.h>

Protocol *protocol = @protocol(UITableViewDelegate);

BOOL showRequiredMethods = NO;
BOOL showInstanceMethods = YES;

unsigned int methodCount = 0;
struct objc_method_description *methods = protocol_copyMethodDescriptionList(protocol, showrequiredMethods, showInstanceMethods, &methodCount);

NSLog(@"%d required instance methods found:", methodCount);

for (int i = 0; i < methodCount; i++)
{
    struct objc_method_description methodDescription = methods[i];
    NSLog(@"Method #%d: %@", i, NSStringFromSelector(methodDescription.name));
}

free(methods)

唯一需要注意的是,在 protocol_copyMethodDescriptionList 中,您需要指定是否需要必需的方法和非必需的方法,以及是否需要类方法和实例方法。因此,要涵盖所有四种情况,您需要调用 protocol_copyMethodDescriptionList 四次并打印每个列表的结果。

【讨论】:

  • @dreamlax 正确,谢谢 - 在普通应用程序中,您肯定会考虑手动内存管理
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-17
相关资源
最近更新 更多