Objective-C在void方法中传递参数

Cha*_*les -7 objective-c

调用void方法时如何传递参数?我知道你可以这样做:

-(void)viewDidLoad {
    [self callMethod];
}

-(void)callMethod {
     //stuff here
}
Run Code Online (Sandbox Code Playgroud)

但是我如何将参数(例如a)传递NSStringcallMethod方法?

Con*_*nor 7

这是一个带整数参数的例子.

-(void)viewDidLoad {
    [self callMethodWithCount:10];
}

-(void)callMethodWithCount:(NSInteger)count {
     //stuff here
}
Run Code Online (Sandbox Code Playgroud)

在objective-c中,参数包含在方法名称中.您可以添加多个参数,如下所示:

-(void)viewDidLoad {
    [self callMethodWithCount:10 animated:YES];
}

-(void)callMethodWithCount:(NSInteger)count animated:(BOOL)animate{
     //stuff here
}
Run Code Online (Sandbox Code Playgroud)

看起来你可能误解了方法开头的空白意味着什么.这是回报值.对于void方法,调用该方法不会返回任何内容.如果你想从你的方法返回一个值,你会这样做:

-(void)viewDidLoad {
    int myInt = [self callMethodWithCount:10 animated:YES];
}

-(int)callMethodWithCount:(NSInteger)count animated:(BOOL)animate{
     return 10;
}
Run Code Online (Sandbox Code Playgroud)

您可以定义返回int的方法(在此示例中,它始终返回10.)然后,您可以将整数设置为通过调用方法返回的值.