gpt4 book ai didi

ios - 所有子类的 class_copyPropertyList 也

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:42:28 25 4
gpt4 key购买 nike

这里是解释
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。

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

最佳答案

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

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

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com