0

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?

albert
  • 8,285
  • 3
  • 19
  • 32
Martin CR
  • 1,250
  • 13
  • 25

1 Answers1

3

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.

Adam Wright
  • 48,938
  • 12
  • 131
  • 152
  • 1
    And here is the documentation that reiterates what Adam says: https://developer.apple.com/library/ios/documentation/General/Conceptual/DevPedia-CocoaCore/AccessorMethod.html – Ricky Nelson Jun 28 '15 at 11:55