Reputation: 14408
New to Objective-C, and i am basically from c++ background. I am learning now objective-c and would like to get confirmation of what i understood is write or wrong?. Kindly advise.
I have the following class:
@interface Test: NSObject
{
int instance1;
}
@property int instance1;
- (void) sayHello;
@end
Class 'Test' has a instance variable instance1
. If the member function ie: sayHello wants to access the variable, it has to happen through getter/setter functions. So, There are two ways to get it :
So, Untimately, getter/setter is the only way to access the variable in the method implementation, ie. both self.instance1 = 100;
and instance1 = 100
need getter/setter.
Having missed both 1. and 2., there is no way to access the instance1
variable.
Also, instance1
is a pubic variable can can be accessed outside of the class with object instance.
Test *t = [[ Test alloc] init];
t.instance1 = 200;
Questions:
instance1
is "private", so that I can not access the instance
variable outside the class?Upvotes: 1
Views: 1264
Reputation: 3228
ion SomeDelegate.h
@interface SomeDelegate : NSWindowController {
@private
int fLanguage;
int fDBID;
bool fEndEditingIsReturn;
@public
int fIsMyLastMSG;
}
@property int language;
In SomeDelegate.mm
@implementation SomeDelegate
@synthesize language=fLanguage;
In my example you get private and public variables, private variable fLanguage
has a property
for synthesize accessor methods.
Upvotes: 1
Reputation: 40201
If the member function ie: sayHello wants to access the variable, it has to happen through getter/setter functions.
It doesn't have to
. You can access ivars directly, without using accessor methods:
- (void)sayHello {
instance1 = 123;
}
You can define private ivars by declaring them in the implementation file, not the header:
@implementation Test {
int privateVar;
}
// ... additional implementation, methods etc.
@end
Note, that since Xcode 4.4 you don't have to declare your ivars anymore. You simply declare a property. The ivar and the accessor methods will be synthessized automatically.
For more details, I recommend reading my answer to this question: Declaration of variables
Upvotes: 1