I've noticed that a lot of Apple's interfaces use @private
before their instance variable declarations. Is there a good design reason for this, and is it something I should do?
相关问题
- CALayer - backgroundColor flipped?
- Core Data lightweight migration crashes after App
- back button text does not change
- iOS (objective-c) compression_decode_buffer() retu
- how to find the index position of the ARRAY Where
相关文章
- 现在使用swift开发ios应用好还是swift?
- TCC __TCCAccessRequest_block_invoke
- xcode 4 garbage collection removed?
- Unable to process app at this time due to a genera
- How can I add media attachments to my push notific
- didBeginContact:(SKPhysicsContact *)contact not in
- Custom Marker performance iOS, crash with result “
- Why is my library not able to expand on the CocoaP
Another way of doing it is to declare instance variables in the @implementation section. Such variables are implicitly private. Source: Kochan: Programming in Objective-C, Fourth Edition. p. 199. It is thus not true that the class declaration must show all of the instance variables, as stated by e.James.
The only reason for declaring instance variables in @interface is to allow them to be inherited by a derived class (subclass).
Private instance variables are used to separate interface from implementation. In Objective-C, since the class declaration must show all of the instance variables, there needs to be a way to prevent subclasses from accessing the ones that are part of the internal implementation. Otherwise, other programmers could write code that depends on those internal variables, which would make it impossible for the class designer to make changes to the class internals without breaking existing code.
Looking at it another way, the instance variables that are not marked private are part of a contract with the subclass programmer, whereas the ones marked private are not.
This means that instance variables should usually be marked private so that they can only be accessed through their accessor methods, if at all. Otherwise, someone could easily write a subclass of your class, and simply create an accessor to make any instance variable public.
If you don't want subclasses to be able to access the variables, mark them @private.