Charles Charles - 4 months ago 8
Objective-C Question

Objective-C passing parameters in void method

How would I go about passing parameters when calling a void method? I understand that you can do something like this:

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

-(void)callMethod {
//stuff here
}


But how would I pass a parameter, such as an
NSString
, to the
callMethod
method?

Answer

Here is an example with an integer parameter.

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

-(void)callMethodWithCount:(NSInteger)count {
     //stuff here
}

In objective-c the parameters are included within the method name. You can add multiple parameters like this:

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

-(void)callMethodWithCount:(NSInteger)count animated:(BOOL)animate{
     //stuff here
}

It seems you may be misunderstanding what the void in the beginning of the method means. It's the return value. For a void method, nothing is returned from calling the method. If you wanted to return a value from your method you would do it like this:

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

-(int)callMethodWithCount:(NSInteger)count animated:(BOOL)animate{
     return 10;
}

You define your method to return an int (in this example it always returns 10.) Then you can set an integer to the value returned by calling the method.