代码之家  ›  专栏  ›  技术社区  ›  Neil Middleton

这个语法在Objective-C中是什么意思?

  •  4
  • Neil Middleton  · 技术社区  · 16 年前

    考虑以下事项:

    - (id)initWithTitle:(NSString *)newTitle
         boxOfficeGross:(NSNumber *)newBoxOfficeGross
                summary:(NSString *)newSummary;
    

    3 回复  |  直到 16 年前
        1
  •  5
  •   Dave DeLong    16 年前

    它是一个名为 initWithTitle:boxOfficeGross:summary: 返回类型为的对象 id (通用对象)。它有三个参数:字符串对象、数字对象和另一个字符串对象。

    您可以这样调用它:

    NSNumber * gross = [NSNumber numberWithInteger:1878025999]
    Movie * avatar = [[Movie alloc] initWithTitle:@"Avatar"
                                   boxOfficeGross:gross
                                          summary:@"Pocahontas in the 22nd century"];
    //or you can do it all on one line, like so:
    Movie * avatar = [[Movie alloc] initWithTitle:@"Avatar" boxOfficeGross:gross summary:@"Pocahontas in the 22nd century"];
    
        2
  •  4
  •   mipadi    16 年前
    • - 实例方法 类方法 .
    • (id) 意味着它返回一个 id ,正如你所猜测的。
    • initWithTitle: boxOfficeGross: ,及 summary: 是方法名称的一部分。在Objective-C中,每个参数通常都有一个关联的方法名称部分。方法的全名为 initWithTitle:boxOfficeGross:summary .
    • (NSString *) 等,表示参数的类型。
    • newTitle
        3
  •  0
  •   mjdth    16 年前

    这个 - 指定实例方法,而如果它是 +

    这个 (id) 是方法将返回的内容,它只是对对象的引用。

    : ,例如 [class initWithTitle:@"my title"];

    每个参数有两个名称的原因是,方法本身将通过后面的任何名称引用变量 ,因此标题为 newTitle .

    起初,这让我感到困惑,但也有好处。

    此外,括号内每个参数的部分都是参数的对象类型。 (NSString *) 是指向 NSString . 如果你要通过一个不是 NSObject ,例如 NSIntger ,您将不需要 * . 您只需执行以下操作: -(id)initWithInteger:(NSIntger)newInteger;