在 Objective-C 中以字符串形式获取对象的属性名称

raz*_*r28 5 properties introspection objective-c objective-c-runtime ios

假设您有一个类“Foo”,其属性为“testProperty”。目的是获取属性名称(而不是值)NSString。问题可能与Get property name as a string重复。但这些答案对我没有帮助,因为:

  • 我不需要所有属性。我只需要特定的一个。
  • 对于NSStringFromSelector(@selector(prop))- 无论如何你必须输入字符串。

假设我有一个类似的函数

- (NSString *)propertyToString:(id)propertyOfObject
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我可以使用,例如,排序

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:[self propertyToString:foo.testProperty] ascending:NO]; 
Run Code Online (Sandbox Code Playgroud)

所以最后,代码将会变得干净。

Din*_*uan 0

是不可能的。您想要获取属性名称,但需要传递一些内容以将其与其他属性区分开。