OGeek|极客世界-中国程序员成长平台

标题: ios - 所有子类的 class_copyPropertyList 也 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 08:58
标题: ios - 所有子类的 class_copyPropertyList 也

这里是解释
List of class properties in Objective-C
如何使用 class_copyPropertyList 在运行时获取类的所有属性。

我已经测试过了,它工作正常。
我注意到它只会从该类中获取属性,而不是它的子类。

代码:

@interface JustForThisUT : NSObject
@property NSUInteger public_access;
@end

@interface JustForThisUT ()
@property NSUInteger private_access;
@end

@implementation JustForThisUT
@end



@interface JustForThisUTParent : JustForThisUT
@property NSUInteger my_public_access;
@end

@interface JustForThisUTParent ()
@property NSUInteger my_private_access;
@end

@implementation JustForThisUTParent
@end

如果我在 JustForThisUT 上使用它,我将获得 2 个属性(public_access 和 private_access)
如果我在 JustForThisUTParent 上使用它,我还将获得 2 个属性(my_public_access 和 my_private_access)

但对于 JustForThisUTParent,我期望从 JustForThisUT 获得 4、2 和从 JustForThisUTParent 获得 2。

我的问题是
如何从当前类和所有子类中获取属性?
甚至可能吗?



Best Answer-推荐答案


您必须首先找到所有子类,然后使用 class_copyPropertyList() 列出每个类的属性,根据需要进行唯一化。

但是,这有一种不好的代码味道。这种动态的、大量反射的编程与 ObjC 的真正设计目的背道而驰。您最终会得到一个难以维护的脆弱代码库。

如果您真的想要这种性质的动态,那么在每个类上实现一个类方法,该方法返回您希望能够动态访问的属性名称列表。

关于ios - 所有子类的 class_copyPropertyList 也,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25572690/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4