MrBr
MrBr

Reputation: 1916

Objective-C messaging

I am having trouble to understand the concept of private instance variables in Objective-C:

Let's assume I have a class:

@interface Dog : NSObject

and two declared selectors

- (void)setSomeString:(NSString *)_someString;
- (NSString *)someString;

in the Dog.m implementation file I declare a private instance variable:

@interface Dog()
{
  NSString *someString;
}

in the main method of the program I create a new dog object:

Dog *myDog = [[Dog alloc] init];

Why is it possible to do something like this out of the main method?

myDog.someString = @"Yoda";

I would expect the someString-variable to be private and only accessible by its setter

[myDog setSomeString:@"Yoda"];

Upvotes: 2

Views: 129

Answers (3)

John Corbett
John Corbett

Reputation: 1615

the dot syntax actually calls the setter method. To access the iVar, you can use the arrow syntax ->

Upvotes: 0

wattson12
wattson12

Reputation: 11174

dot notation is just an abbreviation,

self.someVariable = newValue
//is the same as 
[self setSomeVariable:newValue];

and

currentValue = self.someVariable;
//is the same as
currentValue = [self someVariable];

Upvotes: 0

Manlio
Manlio

Reputation: 10865

When you use dot-syntax you are actually calling method setSomeString, the difference is just in syntax, not in meaning :)

Check Apple documentation about sending a message to an object

Upvotes: 4

Related Questions