Reputation: 2565
I am a bit confused about encapsulation. In general (or in Obj-C), does it mean separation of interface/implementation OR does it imply access of ivars through methods ?
Please clarify. Thank you.
Upvotes: 0
Views: 2747
Reputation: 139
Hiding of Class methods and variables from once class to other is called encapsulation.
Upvotes: 0
Reputation: 162712
Actually, Both.
As nacho4d said, you encapsulate instance variables within your class and prevent direct access to them by using methods and properties to read and write their values. This ensures that the instance can always know when something has read or written a value whereas direct ivar access is no different from setting a value in a C struct.
However, the separation of @interface
from @implementation
also contributes greatly to encapsulation. And one of the goals of the enhancements to the language in the past few years has been to increase the degree of encapsulation offered by that separation.
Namely, the class's primary @interface
can now contain only the parts of your class that you want other developers/code to interact with. The public interface, if you will. All of the implementation details can be moved out of the @interface
in the latest compilers, including all instance variables.
Upvotes: 6
Reputation: 45118
The latter. From wikipedia:
A language mechanism for restricting access to some of the object's components.
Specifically in Objective-C an ivar will be @protected by default, so they only can be accessed within the same class or subclasses. can change it to @private or @public as you need.
The methods you mentioned are accessors (getters and setters) and in that case you probably want to use @properties since they can be defined in 1 line and you can set some attributes like retain, assign, copy, readonly, etc. Read further on properties here (Apple doc)
Upvotes: 0