3

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

例如:

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

这是我遇到的问题。我的问题是我不知道[myAppObject theArray]在做什么。它是创建myAppObject的实例还是使用 theArray 方法创建一个同名的类?

任何人都可以阐明这个话题吗?

4

6 回答 6

4

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

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

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

所以:

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

是相同的:

[an_array insertObject:an_object atIndex:0]

于 2013-10-01T15:13:23.010 回答
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];
于 2013-10-01T15:10:24.907 回答
1
  • 如果myAppObject是一个类,那么theArray就是 myAppObject 的一个方法。
  • 如果myAppObject是类的实例,则 theArray是该类的实例方法。

obj.method()Java 或$obj->method()PHP 中也是如此。

于 2013-10-01T15:12:02.430 回答
1

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

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

myAppObject.theArray.insertObjectAtIndex(myAppObject.objectToInsert, 0)
于 2013-10-01T15:12:27.047 回答
1

和做的一样:

NSArray *myarray = [myAppObject theArray];

id object = [myAppObject objectToInsert];

myArray insertObject:object atIndex:0]

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

于 2013-10-01T15:11:32.557 回答
1

该声明是简短版本。否则,您必须这样做; NSArray *array = [myAppObject theArray];// 返回名为 theArray 的数组的对象。

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

于 2013-10-01T15:14:43.720 回答