目标c中的嵌套方法调用

时间:2013-10-01 15:07:55

标签: objective-c

嘿,我刚开始使用objective-c,我遇到了嵌套的消息传递概念。我不明白为什么我们必须使用它以及如何在语法和语义上使用它。

例如:

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

这是我遇到过的。我的问题是我不知道 [myAppObject theArray] 正在做什么。它是创建 myAppObject 的实例还是那个名称的类有 theArray

的方法

有人能否对这个话题有所了解?

6 个答案:

答案 0 :(得分:4)

这是嵌套方法调用的一个例子。简单地:

[myAppObject theArray]正在返回一个数组。

[myAppObject objectToInsert]正在返回一个对象。

所以:

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

与:

相同

[an_array insertObject:an_object atIndex:0]

答案 1 :(得分: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];

答案 2 :(得分:1)

与做:

相同
NSArray *myarray = [myAppObject theArray];

id object = [myAppObject objectToInsert];

myArray insertObject:object atIndex:0]

第一行返回存储在类theArray上的对象myAppObject,即MyAppObject上的实例。

答案 3 :(得分:1)

  • 如果 myAppObject 是一个类,则 theArray 方法 myAppObject。
  • 如果 myAppObject 是一个类的实例,那么 theArray 是该类的实例方法。

与Java中的obj.method()或PHP中的$obj->method()相同。

答案 4 :(得分:1)

[myAppObject theArray] - myAppObject是一个变量,它包含一个类的对象,该类具有方法myArray,它(希望)返回一个数组。

如果您习惯使用其他OOP语言,请以这种方式考虑该行:

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

答案 5 :(得分:1)

此声明是简短版本。其他明智的你必须做这样的事情; NSArray *array = [myAppObject theArray]; //对象返回名为theArray的arry。

之后,它在该数组上调用插入Object方法。 [array insertObject:[myApObject objectTOInsert] atIndex:0]; //在索引0处插入对象。[myAppobject objectToInsert]返回对象,就像我们有数组一样。