Why does my Objective-C dot accessor behaves differently with an implicit getter?

78 views Asked by At

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?

1

There are 1 answers

1
Adam Wright On BEST ANSWER

Remember that Objective C getters are just the name of the property; foo in the foo case. In this, there's no relationship between getFoo and foo, so you access the underlying property via its normal getter. It's never been set, so it's nil, which logs as null.

In the later case, you establish the getter for bar as getBar. Thus, accessing bar the property evaluates the getter function you specified.