我想在运行时弄清楚某个类的属性是否可为空。例如:在运行时检查ObjC属性是否可为空
@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
应该在这种情况下,与@"error"
返回NSSet
。
property_getAttributes
功能可以提供一些属性的信息(更多信息here)。不幸的是,它没有提供有关该财产是否被宣布为可空的信息。
我想避免对每个需要知道可为null属性的类实现nullableProperties
。
'nullable'修饰符只是编译器的信息,可以帮助它向Swift提供适当的接口;它不修改编译的代码。 – Paulw11
据我所知,您不能使用'class'(+)函数获取声明的变量值。检查你的代码是否有错误 – user3589771
预编译脚本来抓取属性信息并插入方法decl? libclang很容易使用,尽管我不知道它是否公开了这个属性。 –