views:

105

answers:

3

Hi All,

I will explain my question from an example.

In .H file//

@interface Employee:NSObject{

@private

NSString *name;

}

@property(nonatomic,retain) NSString *name;

in .M file//

@implementation{

@synthesize name;

}

In this scenario when i access the name property within another class , like myEmp.Name = @"John"; it doesn't raise any issue. Does this according to the encapsulation rules or am I misunderstanding?

+4  A: 

You did not break encapsulation rules, because the @property(nonatomic,retain) NSString *name; already indicates you want to expose the getters/setters for name.

Encapsulation is broken only when you access the ivar directly, i.e.

myEmp->name = @"John";  // wrong
KennyTM
Why was this downvoted? Seems right to me.
Deepak
+3  A: 

I think you have misunderstood what @property and @synthesize are for. They are convenience ways to define accessor methods. ie. what you have is equivalent to:-

- (NSString *)name;
- (void)setName:(NSString *)value;

myEmp.name = @"John" is syntactic sugar for [myEmp setName:@"John"]

So you explicitly created optional public accessor methods and then used them. No encapsulation broken here.

mustISignUp
A: 

In Objective-C, only an instance method of object can access an instance variable. There is no way for an external object to access the instance variables of an object directly. The @private is only relevant to inheritance.

To make the variables accessable there are properties. A property defines a method, and methods on Objective-C are all public. There is no way in Objective-C do define private methods, you can only "hide" them by declaring them somewhere else than the public .h file (e.g. inside the .m file via @interface Employee() which declares an anonymous section).

DarkDust
It is trivially easy to access ivars directly from external objects, regardless of the presence or absence of `@private`.
bbum
@bbum: You're right, I was assuming that Objective-C behaves the same as Ruby here...
DarkDust