标题中的许多方法的声明

时间:2012-08-27 22:31:01

标签: objective-c

我试图学习obj-c,这是我不明白的东西。我知道一些c#所以有人试图用c#y-way解释这个问题我可能会更好地理解它:)

#import <Foundation/Foundation.h> @interface Car : NSObject
@interface Car : NSObject
  {
  int year;
  NSString *make;
  NSString *model;
  }

  **- (void) setMake:(NSString *) aMake andModel:(NSString *) aModel andYear: (int) aYear;**
  - (void) printCarInfo;
  - (int) year;
@end

我认为我理解变量的声明,但我没有得到它的metod(s?)。有人可以解释一下(粗体代码)吗?

2 个答案:

答案 0 :(得分:2)

你学习中缺少的概念是“选择器”。它实际上就像“装饰”一个方法签名,其语义比用括号参数传递更多。我们倾向于使用描述性的,类似句子的“选择器”作为我们的方法原型。例如,考虑这个基本功能:

void function setDimensions(int width, int height);
在Objective-C中,我们会这样写:

- (void) setWidth:(int) newWidth height:(int) newHeight;

和“选择器”(which is a first-class concept in Objective-C)是 setWith:height:(包括冒号,但不包括任何其他内容)。那是唯一标识该类上该方法的 thing

当您向该对象发送消息并且在选择器中的冒号后面放置参数时,调用该方法会在运行时发生。因此,消息有三个基本组件:收件人,选择器和放置好的参数:

[anObject setWidth: 1024 height: 768];

此处,anObject是收件人,setWidth:height:是选择器(帮助运行时查找方法),参数为:newWidth = 1024; newHeight = 768;

然后在方法的实现中,只需使用newWidth和newHeight就像你期望的那样:

- (void) setWidth:(int) newWidth height:(int) newHeight; {
    self.width = newWidth; // 1024
    self.height = newHeight; // 768
}

起初看起来似乎很尴尬和多余,但是在你习惯它之后,你会更喜欢它,并发现自己在其他语言中编写更长,更语义的函数名称。

the Objective-C runtime 的一些基础知识一起学习时,可以更好地理解与选择器相关的概念,特别是“发送消息”的概念(而不是“调用方法”)并且在运行时,而不是编译时的事实是根据您在消息中使用的选择器查找实际方法。这种情况在运行时发生,为高度动态的架构提供了极大的灵活性。

答案 1 :(得分:0)

在Objective-C方法中有命名参数。方法声明语法如下:

- (returnValue)nameOfArgument1:(typeOfArgument1)nameOfVariable1 
               nameOfArgument2:(typeOfArgument2)nameOfVariable2 
               nameOfArgument3:(typeOfArgument3)nameOfVariable3;

换行符当然是可选的,但您需要将参数与至少一个空格分开。第一行上的 - 符号表示这是一个实例方法(与类方法相反,它应该以+符号开头)。

.m文件中的实现看起来完全一样,除了用实现替换分号:

- (returnValue)nameOfArgument1:(typeOfArgument1)nameOfVariable1 
               nameOfArgument2:(typeOfArgument2)nameOfVariable2 
               nameOfArgument3:(typeOfArgument3)nameOfVariable3 {
    // Implementation
    // Return something of type "returnValue".
}

你可以从其他地方调用这个方法:

[myObject nameOfArgument1:variableToPass1 
          nameOfArgument2:variableToPass2
          nameOfArgument3:variableToPass3];

我希望这会使事情变得更清楚。

相关问题