我想创建一个函数数组,以便我可以随机化这些数组发生的顺序。 我可以这样做:
NSMutableArray *MyArray = [NSMutableArray arrayWithObjects: function1, function2, function3, nil];
所以,如果我能做这样的事情,那么
RandomNum = arc4random() %([MyArray count]);
MyArray[RandomNum];
这样随机化调用这些函数的顺序? 如何将函数存储在此数组中?
答案 0 :(得分:4)
对于ObjC阻止,您可以直接将它们存储在NSArray
中。普通C函数必须包含在NSValue
:
NSArray *functions = @[[NSValue valueWithPointer:function1], [NSValue valueWithPointer:function2]];
然后您可以按照以下方式调用它们,只需确保将其转换为正确的签名:
((void (*)(int))[functions[RandomNum] pointerValue])(10);
答案 1 :(得分:4)
有想法的方法
样本1 - 块
NSMutableArray *array = [NSMutableArray array];
[array addObject:^{ /* block */ }];
样本2 - 调用
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[object methodSignatureForSelector:selector]];
invocation.target = object;
invocation.selector = selector;
[array addObject:invocation];
样本3 - C函数
[NSValue valueWithPointer:function1]
答案 2 :(得分:1)
阻止将是最好的方法,但我不熟悉你可以使用的阻止或蚂蚁其他原因:NSSelectorFromString& NSStringFromSelector
<强> EDITED 强>
NSStringFromSelector
NSSelectorFromString
调用函数。例如
NSArray * functions = @[NSStringFromSelector(selector1),NSStringFromSelector(selector2),
NSStringFromSelector(selector3),NSStringFromSelector(selector4)];
//shuffle the array (see link)
[functions shuffle];
[arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[self performSelector:NSSelectorFromString(functions[idx]) withObject:nil];
}];
(代码是动态编写的,请查看)。
答案 3 :(得分:1)
存储指向数组中函数的指针并调用函数:
#import <Foundation/Foundation.h>
static void hello() {
NSLog(@"hey\n");
}
int main(int argc, char *argv[]) {
@autoreleasepool {
NSPointerArray *array = [NSPointerArray pointerArrayWithOptions:NSPointerFunctionsOpaqueMemory];
[array addPointer: &hello];
void* ptr = [array pointerAtIndex:0];
((void (*)(void)) ptr)(); // prints hey
}
}