Search code examples
objective-cnullableintrospectiondeclared-property

Checking whether an ObjC property is nullable at runtime


I'm trying to figure out at runtime whether a property of a class is nullable. For example:

@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 should in this case return an NSSet with @"error".

property_getAttributes function can provide information of some of the attributes (more info here). Unfortunately, it doesn't provide information on whether the property is declared as nullable.

I would like to avoid implementing nullableProperties for every class that I need to know the nullable properties for.


Solution

  • Every Objective-C pointer or object property is technically nullable at runtime. The nullability specifiers are simply compiler hints that don't affect the actual built binary [edit: by which I mean, since this is apparently unclear, the 1s and 0s that get written to the disk in either Mach-O or some other comparable binary format by the compiler and linker, and which contain the machine instructions that represent the program logic along with other information and metadata]. Therefore, there's no way to detect at runtime which properties are nullable and which are not.