2013-10-01 105 views
3

嘿,我剛剛開始與Objective-C和我遇到了嵌套消息的概念。我不明白爲什麼我們必須使用以及它如何使用語法和語義。嵌套方法調用客觀c

例如:

[[myAppObject theArray] insertObject:[myAppObject objectToInsert] atIndex:0]  

這是一個我來到across.My問題是,我不知道是什麼[myAppObject theArray]是doing.Is它創造的myAppObject或實例有沒有一個類的名稱與方法theArray

任何人都可以點亮這個主題?

+1

@AndreyChernukha:這是一個有效的問題。 – Linuxios

回答

3

是否創建myAppObject的實例或者是有一個類由 名稱與方法theArray

既不; myAppObject是類MyAppObject(假定使用傳統命名)的實例,並且實例方法或屬性theArray正在該實例上發送消息。

所以MyAppObject會是這個樣子:

@interface MyAppObject : NSObject { 
    NSArray *_theArray; // This is optional, and considered to be old fashioned 
          // (but not by me). 
} 

@property (nonatomic, strong) NSArray *theArray; 

... 

@end 

已經分配是這樣,地方:

MyAppObject *myAppObject = [[MyAppObject alloc] init]; 
1

是一樣的做:

NSArray *myarray = [myAppObject theArray]; 

id object = [myAppObject objectToInsert]; 

myArray insertObject:object atIndex:0] 

第一行返回存儲在類0上的對象,這是MyAppObject上的一個實例。

1
  • 如果myAppObject是一個類,然後theArray是 myAppObject的方法。
  • 如果myAppObject是一個類的實例,然後 theArray是那個類的一個實例方法

這與在Java中的obj.method()或在PHP中的$obj->method()是一樣的。

1

[myAppObject theArray] - myAppObject是一個變量,它包含一個類的對象,該類的對象具有方法myArray,這是(希望)返回一個數組。

如果你使用的其他OOP語言,認爲行是這樣的:

myAppObject.theArray.insertObjectAtIndex(myAppObject.objectToInsert, 0) 
4

即嵌套的方法調用的一個例子。簡單地說:

[myAppObject theArray]正在返回一個數組。

[myAppObject objectToInsert]正在返回一個對象。

所以:

[[myAppObject theArray] insertObject:[myAppObject objectToInsert] atIndex:0]

是一樣的:

[an_array insertObject:an_object atIndex:0]

1

這種說法是短版。其他方面,你必須做這樣的事情; NSArray *array = [myAppObject theArray]; //對象返回名爲theArray的arry。

之後,它調用該數組插入對象方法。 [array insertObject:[myApObject objectTOInsert] atIndex:0]; //在索引0處插入對象。[myAppobject objectToInsert]返回對象與我們獲得數組相同。