Difference between @interface declaration and @property declaration

前端 未结 6 2027
忘了有多久
忘了有多久 2020-12-23 10:05

I\'m new to C, new to objective C. For an iPhone subclass, Im declaring variables I want to be visible to all methods in a class into the @interface class definition eg

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-23 10:25

    Classes can have instance variables (ivars). These are in the first section, and are only visible to code in that class, not any outside code. I like to prefix them with an underscore to show their internal-ness. In low level terms, the ivars are added as an additional member to the struct that the class you are creating uses internally.

    The second declaration, @property, is a declared property. It is not required (except when you are using @synthesize), but it helps other programmers (and the compiler!) know that you are dealing with a property, and not just two methods -setAVar and -aVar, which is the alternative way of doing this.

    Thirdly, the @synthesize actually creates the methods to set and access the property from outside the class. You can replace this with your own setter and getter methods, but only do that if you need to, as the built-in ones have some features that you would otherwise have to code yourself. In fact, using the @synthesize aVar = _someVariable; syntax, you can have your property actually reference a differently named instance variable!

    Short version: The @property is just a hint to the compiler and other programmers that you are making a property and not just getter/setter methods. The instance variables are internal to the class, and otherwise cannot be normally accessed from outside it. The @synthesize just creates simple getters and setters for you, to go with your @property, but you can also just code those getters and setters yourself, like any other method.

提交回复
热议问题