Newbee
Newbee

Reputation: 3301

How to access other class members(ivars) in a class without making it public?

I have wrote the following objective c class..

@interface thumb_user_info : NSObject
{
@public // Otherwise I was not able to access in other class.
    NSString *user_name;
    int       user_id;
}
@end

When I create instance in other class and try to set value for the user_id, it shows error "it is protected", how to access those ivars without making it public like above. I know its very basics in objective C, I don't want to hesitate to make myself clear.

NOTE: I have tried by synthesis it also... still same error...

thanks.

Upvotes: 1

Views: 118

Answers (2)

Anoop Vaidya
Anoop Vaidya

Reputation: 46563

The thing you are asking is one of the fundamental of OOP, Object Oriented Programming.

You encapsulate, bind, hide your private property from outside world by making it private.

If you want them visible you make it public.

If you wnat them to be hidden but inheritable you make it protected.

So, no way to access your private ivars/methods from outside self class.

If you want to access private ivars value, then make a public method and indirectly get/return the value.

synthesize creates methods for the ivars (private/protected/public), if it is in .h it becomes public.

Upvotes: 3

Guo Luchuan
Guo Luchuan

Reputation: 4731

It is instance var , not property , so you can not set value for them by yourclass.user_name = userName , I think you should better add some method to set the value such as :

- (void)setupUserName:(NSString *)userName
{
    user_name = userName
}

Upvotes: 2

Related Questions