这段代码获取对象 属性 的名称意味着什么?

What dose this code means to get the name of the property of an object?

#define propertyKeyPath(property)(@""#property)

如果我这样使用这个宏:

NSLog(@"%@",propertyKeyPath(self.someProperty)); 

我会得到self.someProperty

我想知道它是如何工作的,谢谢。

这是我看到这种用法的网站:“http://www.g8production.com/post/78429904103/get-property-name-as-string-without-using-the

您更正后:

#define propertyKeyPath(property)(@""#property)

这个宏所做的是将其参数转换为字符串。

宏通过文本扩展工作 - 它们的扩展被插入到编译器看到的文本中,然后编译器分析结果。在带有 # 的参数前面的宏中,将参数作为 C 字符串插入到宏的扩展中。所以你的宏调用:

propertyKeyPath(self.someProperty)

扩展为:

(@"""self.someProperty")

现在源代码中两个相邻的 C 字符串由编译器连接(这通常用作分解大字符串以便于键入和阅读的方法)。扩展有两个相邻的字符串:"""self.someProperty" 所以它们被连接起来只产生 "self.someProperty" 并且你的文本现在看起来像:

(@"self.someProperty")

编译为 Objective-C 字符串文字。

这就是它的作用,至于为什么使用宏而不是直接写字符串文字我不能说。

HTH