如何在Objective-C中建立类方法的NSArray(或NSMutableArray)? [英] How to build a NSArray (or NSMutableArray) of class methods in Objective-C?

查看:68
本文介绍了如何在Objective-C中建立类方法的NSArray(或NSMutableArray)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Objective-C 中构建方法的NSArray.

I'm trying to build a NSArray of methods in Objective-C.

(我想在这里完成的工作类似于C中的以下内容)

(What I'm trying to accomplish here is something like the following in C)

typedef (void)(*handler)(int command);

void handleCommandA(void) { ... }
void handleCommandB(void) { ... }

static const handler handler_table[10] = {
    handleCommandA, handleCommandB, handleCommandC
};

我必须将此移植到Objective-C,但我不知道该如何 构建一个函数指针数组(在Objective-c世界中, 类方法).

I have to port this to Objective-C and I don't know how to build an array of function pointers (in Objective-c world, class methods) at compile-time.

在Objective-C中,我有以下内容.

In Objective-C I have the following.

- (void)handleCommandA { ... }
- (void)handleCommandB { ... }

/* Now how to add above 2 functions into NSArray? */
NSArray *handler_table = [NSArray arrayWithObjects:... ];  /* This doesn't seem to work. */

推荐答案

使用NSValue.

Use NSValue.

例如:

NSArray* handlers = [NSArray arrayWithObjects:[NSValue valueWithPointer:handleA] ... ];

然后访问:

handleptr* handle = (handlerptr*)[[handlers objectAtIndex:0] pointerValue];
handle(foo_bar);

这篇关于如何在Objective-C中建立类方法的NSArray(或NSMutableArray)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆