【发布时间】:2017-08-22 10:46:25
【问题描述】:
我试图在运行时确定一个类的属性是否可以为空。例如:
@interface A : NSObject
+ (NSSet<NSString *> *)nullableProperties;
@property (readonly, nonatomic) NSString *description;
@property (readonly, nonatomic, nullable) NSError *error;
@end
@implementation A
+ (NSSet<NSString *> *)nullableProperties {
// Code that identifies nullable properties.
}
@end
nullableProperties 在这种情况下应该返回一个NSSet 和@"error"。
property_getAttributes函数可以提供一些属性的信息(更多信息here)。不幸的是,它没有提供有关该属性是否被声明为可为空的信息。
我想避免为每个我需要知道其可为空属性的类实现nullableProperties。
【问题讨论】:
-
nullable修饰符只是给编译器的信息,帮助它为 Swift 提供适当的接口;它不会修改编译后的代码。 -
据我所知,您无法使用
class(+) 函数获取声明的变量值。如果有任何问题,请检查您的代码。 -
预编译脚本来抓取属性信息并插入方法decl? libclang 很容易使用,虽然我不知道它是否公开了这个属性。
标签: objective-c nullable introspection declared-property