Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C passing methods as parameters

How do you pass one method as a parameter to another method? I'm doing this across classes.

Class A:

+ (void)theBigFunction:(?)func{
    // run the func here
}

Class B:

- (void)littleBFunction {
    NSLog(@"classB little function");
}

// somewhere else in the class
[ClassA theBigFunction:littleBFunction]

Class C:

- (void)littleCFunction {
    NSLog(@"classC little function");
}

// somewhere else in the class
[ClassA theBigFunction:littleCFunction]
like image 803
Jacksonkr Avatar asked Oct 29 '11 01:10

Jacksonkr


People also ask

How do you pass a function as a parameter in Objective-C?

Objective-C programming language allows you to pass a pointer to a function. To do so, simply declare the function parameter as a pointer type.

Is Objective-C pass by reference?

The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call.


2 Answers

The type you are looking for is selector (SEL) and you get a method's selector like this:

SEL littleSelector = @selector(littleMethod); 

If the method takes parameters, you just put : where they go, like this:

SEL littleSelector = @selector(littleMethodWithSomething:andSomethingElse:); 

Also, methods are not really functions, they are used to send messages to specific class (when starting with +) or specific instance of it (when starting with -). Functions are C-type that doesn't really have a "target" like methods do.

Once you get a selector, you call that method on your target (be it class or instance) like this:

[target performSelector:someSelector]; 

A good example of this is UIControl's addTarget:action:forControlEvents: method you usually use when creating UIButton or some other control objects programmatically.

like image 146
Filip Radelic Avatar answered Sep 20 '22 05:09

Filip Radelic


Another option is to look at blocks. It allows you to pass a block of code (a closure) around.

Here's a good write up on blocks:

http://pragmaticstudio.com/blog/2010/7/28/ios4-blocks-1

Here's the apple docs:

http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Blocks/Articles/00_Introduction.html

like image 26
bryanmac Avatar answered Sep 19 '22 05:09

bryanmac