@property and @synthesize in objective-c

后端 未结 2 579
旧时难觅i
旧时难觅i 2020-12-24 02:54

While I was playing and figure out how things work in https://github.com/enormego/EGOTableViewPullRefresh I found mysterious of @property and @synthesize. Here is the code I

2条回答
  •  醉酒成梦
    2020-12-24 03:46

    You are right, using

    @synthesize foobar=_foobar;

    is a bit pointless in most cases , but at an abstract level it does allow you to return the value of some other variable entirely. As in ...

    @synthesize foobar=fluffybunny;

    Lets you get or set the value of fluffybunny each time you use the accessor .foobar

    However in terms of the@synthesize complexity , would you rather write

    -(void)setFoobar:(id)aobject {
        [self willSetValueForKey:"foobar"];
        id old = foobar;
        foobar = [aobject retain];
        [old release];
        [self didSetValueForKey:"foobar"];
    }
    
    -(id)foobar {
        [self willAccessValueForKey:"foobar"];
        id obj = [self primitiveValueForKey:@"foobar"];
        [self didAccessValueForKey:"foobar"];    
        return obj;
    }
    

    Or

    @synthesize foobar;
    

    Thats not particularly well written as ive forgotten how to do them well but the @synthesize directive stops you having to write accessors so many times. It one one of the things that sucked heavily about Obj-C 1.0.

    Free code , dont knock it.

提交回复
热议问题