Reason to use ivars vs properties in objective c

前端 未结 5 1435
说谎
说谎 2020-11-27 05:50

I have been unable to find any information on this topic and most of what I know about it has come by complete accident (and a few hours of trying to figure out why my code

5条回答
  •  温柔的废话
    2020-11-27 06:06

    I typically just use @property and @synthenize.

    @property gives the compiler and the user directions on how to use your property. weather it has a setter, what that setter is. What type of value it expects and returns. These instructions are then used by the autocomplete (and ultimately the code that will compile against the class) and by the @synthesize

    @synthesize will by default create an instance variable with the same name as your property (this can get confusing)

    I typically do the following

    @synthesize propertyItem = _propertyItem; 
    

    this will by default create a getter and a setter and handle the autorelease as well as create the instance variable. The instance variable it uses is _propertyItem. if you want to access the instance variable you can use it as such.

    _propertyItem = @"Blah";
    

    this is a mistake tho. You should always use the getter and setter. this will let the app release and renew as needed.

    self.propertyItem = @"Blah";
    

    This is the better way to handle it. And the reason for using the = _propertyItem section of synthesize is so you cannot do the following.

    propertyItem = @"Blah"; // this will not work.
    

    it will recommend you replace it with _propertyItem. but you should use self.propertyItem instead.

    I hope that information helps.

提交回复
热议问题