1

Let's say that I declare property in following way:

@property(nonatomic, strong, getter = isWorking) BOOL working;

Then instead of having the property to be synthesized I write the getter myself (and add some custom logic to it).

What will happen if I access the property in following way:

BOOL work = self.working;

Is the getter (and my custom logic there) still called or is it called only when I access the property using getter explicitly (BOOL work = self.isWorking;) ?

4

1 回答 1

3

哎呀。 刚试了一下。显然我使用点符号太多了,并没有意识到它做了多少。:P

#import "NSObject.h"
#include <stdio.h>

@interface Test : NSObject
@property (getter=myStuff) int stuff;
@end

@implementation Test
-(int)myStuff { return 42; }
-(void)setStuff:(int)value { /* don't care */ }
@end


int main() {
    @autoreleasepool {
        Test* test = [[Test alloc] init];

        /* All these work... */
        printf("test.stuff == %d\n", test.stuff);
        printf("[test myStuff] == %d\n", [test myStuff]);
        printf("test.myStuff == %d\n", test.myStuff);

        /* but here, there's an exception */
        printf("[test stuff] == %d\n", [test stuff]);

        return 0;
    }
}

当我编译这个(在 Linux 中使用 clang)时,有两个关于缺少的奇怪的警告-(int)stuff。输出看起来像

chao@chao-VirtualBox:~/code/objc$ ./a.out
test.stuff == 42
[test myStuff] == 42
test.myStuff == 42
: Uncaught exception NSInvalidArgumentException, reason: -[Test stuff]: unrecognized selector sent to instance 0x2367f38
chao@chao-VirtualBox:~/code/objc$ 

所以,嗯,是的。忽略下面一半的东西。:P


self.working只是语法糖[self working](或者[self setWorking:value]如果你分配给它)。任何一个都会做同样的事情:返回 的值 [self isWorking],因为那是您定义的 getter。

如果您想避免使用吸气剂,请尝试_workingself->_working(或您命名为 ivar 的任何名称)。否则,self.working和( 即使你感觉很勇敢)都应该给你相同的结果。[self working][self isWorking]self.isWorking

于 2013-08-17T17:55:07.587 回答