Search code examples
arraysobjective-cfunction

Can you store functions in an array in Objective-C?


I want to make an array of functions so that I could randomize the order in which the functions are called. Could I do something like:

NSMutableArray *MyArray =
    [NSMutableArray arrayWithObjects: function1, function2, function3, nil];

So that I could then do something like this:

RandomNum = arc4random() %([MyArray count]);
MyArray[RandomNum];

Thus randomizing the order in which these functions are called?

How do I store functions in an array?


Solution

  • As for ObjC blocks you can just store them in an NSArray directly. Plain C functions have to be wrapped into an NSValue:

    NSArray *functions = @[[NSValue valueWithPointer:function1], [NSValue valueWithPointer:function2]];
    

    Then you can call them as follow, just make sure you cast it to correct signature:

    ((void (*)(int))[functions[RandomNum] pointerValue])(10);