2012-07-30 22 views
2

我無法理解的Objective-C的私有實例變量的概念:Objective-C的消息

假設我有一個類:

@interface Dog : NSObject 

和兩個宣佈選擇

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

在Dog.m實現文件中我聲明瞭一個私有實例變量:

@interface Dog() 
{ 
    NSString *someString; 
} 
在我創建了一個新的狗對象中的程序的主要方法

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

爲什麼能夠這樣做出來的主要方法?

myDog.someString = @"Yoda"; 

我期望someString變量是私有的,只能訪問其二傳手

[myDog setSomeString:@"Yoda"]; 

回答

4

當你使用你實際上是調用方法setSomeString點語法,所不同的只是在語法,沒有意義:)

檢查Apple documentation有關發送消息的對象

+0

它會自動調用它?這並不令人困惑。我正在閱讀Apple Doc,但我發現它有點不清楚。 – MrBr 2012-07-30 15:02:53

+0

好吧我看到'點運算符爲調用對象的存取方法提供了一種緊湊且方便的語法。點運算符經常與聲明的屬性特徵(...)' – MrBr 2012-07-30 15:03:40

0

點符號只是一個縮寫,

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

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

點語法實際上是調用setter方法。要訪問iVar,您可以使用箭頭語法->

+0

一起使用,它不會爲私有或受保護的ivar編譯。 – 2012-07-31 00:15:05

+0

這是正確的,我只是說這是如何做到的。您需要將ivars聲明爲@public – 2012-07-31 06:37:12