In the following code, I get '(null)' for the second line in the output but not the fourth.
MyClass.h
@interface MyClass : NSObject
@property (readonly) NSString *foo;
@property (getter=getBar, readonly) NSString *bar;
@end
main.m
@implementation MyClass
- (NSString *)getFoo { return @"foo"; }
- (NSString *)getBar { return @"bar"; }
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
MyClass *myClassInstance = [MyClass new];
NSLog(@"%@", myClassInstance.getFoo);
NSLog(@"%@", myClassInstance.foo);
NSLog(@"%@", myClassInstance.getBar);
NSLog(@"%@", myClassInstance.bar);
}
return 0;
output
foo
(null)
bar
bar
Why am I seeing this?
Remember that Objective C getters are just the name of the property;
foo
in thefoo
case. In this, there's no relationship betweengetFoo
andfoo
, so you access the underlying property via its normal getter. It's never been set, so it'snil
, which logs asnull
.In the later case, you establish the getter for
bar
asgetBar
. Thus, accessingbar
the property evaluates the getter function you specified.