Can I give a property an alternate key name in Objective-C?

50 views Asked by At

Can I give a property in an Objective-C class an alternate name so that I can set the property using a different key than it's property name? Here is some example code.

@interface Address : NSObject
@property (strong, nonatomic) NSNumber *apartmentNumber;
@end

// ...

Address *address = [Address new];
address setValue:@(123) forKey:@"apartmentNumber"];

Is it possible to access this property using an alternate key name like "apt"?

Address *address = [Address new];
[address setValue:@(123) forKey:@"apt"];
2

There are 2 answers

3
Berry Blue On BEST ANSWER

Based on the feedback this seems to work without having to write any additional methods.

@interface Address : NSObject
@property (strong, nonatomic, getter=apt, setter=setApt:) NSNumber *apartmentNumber;
@end
0
Gerd K On

You can implement a custom setter method:

- (void)setApt:(NSNumber *)apt {
    
    self.apartmentNumber=apt;
}

And a getter if needed:

- (NSNumber *)apt {
    
    return self.apartmentNumber;
}