Objective c 目标c中的嵌套方法调用

Objective c 目标c中的嵌套方法调用,objective-c,Objective C,嘿,我刚开始使用objective-c,我遇到了嵌套消息传递的概念。我不明白为什么我们必须使用它,以及它在语法和语义上是如何使用的 例如: [[myAppObject theArray] insertObject:[myAppObject objectToInsert] atIndex:0] 这是我遇到的一个。我的问题是我不知道[myAppObject theArray]在做什么。它是在创建myAppObject的实例,还是有一个名为theArray的类 有人能解释一下这个话题吗 它是

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

例如:

[[myAppObject theArray] insertObject:[myAppObject objectToInsert] atIndex:0]    
这是我遇到的一个。我的问题是我不知道[myAppObject theArray]在做什么。它是在创建myAppObject的实例,还是有一个名为theArray的类

有人能解释一下这个话题吗

它是在创建myAppObject的实例,还是有一个这样的类 使用数组的方法命名

都不是
myAppObject
是类
myAppObject
的实例(假设使用了常规命名),并且实例方法或属性
Array
正在就该实例发送消息

所以
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];
与执行以下操作相同:

NSArray *myarray = [myAppObject theArray];

id object = [myAppObject objectToInsert];

myArray insertObject:object atIndex:0]
第一行返回存储在类
myAppObject
上的数组,该类是
myAppObject
上的实例
  • 如果myAppObject是一个类,那么数组是一个类方法 myAppObject
  • 如果myAppObject是类的实例,则 数组是该类的实例方法

  • 这与Java中的
    obj.method()
    或PHP中的
    $obj->method()
    是一样的。

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

    如果您已经习惯了其他OOP语言,可以这样想:

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

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


    [myAppObject theArray]
    正在返回数组

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

    因此:

    [[myAppObject theArray]插入对象:[myAppObject objectToInsert]索引:0]

    同:


    [数组插入对象:索引为0的对象]

    此语句是简短版本。另一方面,你必须这样做;
    NSArray*array=[myAppObject theArray]//返回名为数组的数组的对象

    之后,它将在该数组上调用insert对象方法。
    [array insertObject:[myApObject objectTOInsert]索引:0]
    ;//正在索引0处插入对象
    [myAppobject objectToInsert]
    像我们得到的数组一样重新提取对象。

    @AndreyChernukha:这是一个有效的问题。