我想在運行時弄清楚某個類的屬性是否可爲空。例如:在運行時檢查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很容易使用,儘管我不知道它是否公開了這個屬性。 –