What is the point of @property and @synthesize?

后端 未结 4 549
挽巷
挽巷 2020-12-10 18:08

I haven\'t been able to figure it out, and there are no websites which explain it clearly enough... what exactly are the purposes of @property and @synthe

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-10 18:55

    Just a quick example of why you might not want to do just "variable = 0":

    Say you have this property:

    @property (nonatomic, retain) id  theDelegate;
    

    Whenever you replace that delegate with a new one, your synthesized setters and getters will handle the release/retain for you every time you set it like so:

    self.theDelegate = newObject;
    

    Really what happened was this:

    [self setTheDelegate:newObject];
    
    - (void)setTheDelegate:(id )anObject {
        [theDelegate release];
        theDelegate = [anObject retain];
    }
    

    (This is simplified of course)

    You can do very powerful things in your own setters and getters, synthesize is for those that happen over and over like retained properties, etc. When compiling it looks at your @property and builds the methods accordingly.

提交回复
热议问题