Objective-C Runtime 学习分享 ( 1) class_getName 文档错误

2015-08-12 21:40:06 +08:00
 banxi1988
class_getName 函数文档
<https://developer.apple.com/library/prerelease/watchos/documentation/Cocoa/Reference/ObjCRuntimeRef/#//apple_ref/c/func/class_getName>
说的是:
> The name of the class, or the empty string if cls is Nil.

这一句 ”the empty string if cls is Nil“ 不对。
实际上不是字符串 "nil"
查看了最新开源的代码 ,也确实返回的是 "nil"

```objc
const char *class_getName(Class cls)
{
if (!cls) return "nil";
assert(cls->isRealized() || cls->isFuture());
return cls->demangledName();
}
```

最近想到的一个学习 Objective-C Runtime 的学习方式就是为 其 API 编写测试简单的测试用例。
如 `class_getName`

```objc

- (void)test_class_getName{
XCTAssert(strcmp("Demo", class_getName([Demo class])) == 0);
const char * actual = class_getName(nil);
XCTAssert(strcmp("nil", actual) == 0);
}
```
2578 次点击
所在节点    iDev
5 条回复
fengjianxinghun
2015-08-13 09:06:09 +08:00
不看不知道。。。非常有用。。
kepenj
2015-08-13 11:41:44 +08:00
可以发到他们官方论坛 去嘲讽他们的工程师~~2333333
black
2015-08-13 13:19:19 +08:00
请好好理解文档,文档描述的是参数为空的话返回空字符串,参数是Class类型,空的Class是Nil而不是nil,文档是正确的。
banxi1988
2015-08-13 16:26:12 +08:00
@black 一开始我也是这样想的, 但是我测试的时候,发现他们是一样的。
查看 objc.h 头文件,发现他们其实是同样的宏定义。

```c
#ifndef Nil
# if __has_feature(cxx_nullptr)
# define Nil nullptr
# else
# define Nil __DARWIN_NULL
# endif
#endif

#ifndef nil
# if __has_feature(cxx_nullptr)
# define nil nullptr
# else
# define nil __DARWIN_NULL
# endif
#endif
```
black
2015-08-13 16:31:31 +08:00
@banxi1988 是的,底层实现是一样的

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/212784

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX