【问题标题】:How to run method with parameters in objective-c? [closed]如何在objective-c中运行带有参数的方法? [关闭]
【发布时间】:2013-12-27 06:06:02
【问题描述】:

如何在 Objective-C 中创建一个方法,每次都可以使用不同的参数运行该方法。例如,我希望能够做这样的事情:

int thisMethod (int thisInt; NSString *thisString) {
    int anotherInt = thisInt+2;
    self.thisLabel.stringValue = thisString;
    return 0;
}

所以在这段代码中,我想用两个可以在方法中使用的参数来运行 thisMethod。 即:

thisMethod(10; @"String");

我需要使用这样的结构吗:

- (int) thisMethod:(id)sender{
    //code here
}

如果是,如何使用参数?

【问题讨论】:

  • 是的,你最好阅读一些教程。 Objective-C 不仅仅是理解时髦的调用语法。
  • 顺便说一句 - 你的第一个 thisMethod 不是一个方法,而是一个函数。

标签: objective-c methods parameters


【解决方案1】:
- (int)thisMethodWithInt:(int)thisInt andString:(NSString *)thisString {
    int anotherInt = thisInt+2;
    self.thisLabel.stringValue = thisString;
    return 0;
}

然后调用方法如下所示:

[self thisMethodWithInt:3 andString:@"My Super String"];

您所描述的是一个 c 函数,而不是一个 Objective-c 函数..

【讨论】:

  • 这也需要在类接口中声明,thisLabel 声明为 @property
  • 没错..我不知道他的设置..当然你也可以传递一个 UI/NSLabel 作为参数,如果你没有那个
【解决方案2】:

您也必须传递标签对象,因为 self 在 C 函数中没有意义。在 Objective-C 中,它是传递给每个方法的隐藏参数,但在 C 函数中,您必须自己传递它(并且使用逗号,而不是分号):

int thisMethod (int thisInt, NSString *thisString, id object) {
    int anotherInt = thisInt+2;
    object.thisLabel.stringValue = thisString;
    return 0;
}

您可能必须显式设置类型,而不是使用id,否则编译器会报错。

同样,使用逗号分隔参数:

thisMethod(10, @"String", self);

【讨论】:

    猜你喜欢
    • 2014-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-17
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多