Objective-C 中的函数指针问题
所以我试图在数组中存储一系列方法(如果有意义的话)。
void *pointer[3];
pointer[0] = &[self rotate];
pointer[1] = &[self move];
pointer[2] = &[self attack];
//...
我想做的是拥有一个数组,并根据数组中对象的类型调用某个方法。而不是有一堆 if 语句说这样的话:
if ([[myArray objectAtIndex:0] type] == robot]) {
//Do what robots do...
}
else if (...) {
}
else {
}
并将其放在计时器中,我希望将其做成这样:
pointer[[[myArray objectAtIndex:0] type]]; //This should invoke the appropriate method stored in the pointer.
现在上面的代码说(第一个代码块):
左值需要为一元“&”操作数。
如果您需要任何澄清,请询问。
另外,只是为了让您知道我调用的所有方法都是 void 类型并且没有任何参数。
So I am trying to store a series of methods in an array (if that made sense).
void *pointer[3];
pointer[0] = &[self rotate];
pointer[1] = &[self move];
pointer[2] = &[self attack];
//...
What I am trying to do is have an array of stuff and based on the type of the object in the array, a certain method is invoked. And instead of having a bunch of if statement saying something like:
if ([[myArray objectAtIndex:0] type] == robot]) {
//Do what robots do...
}
else if (...) {
}
else {
}
And having this in a timer I was hoping to make it something like this:
pointer[[[myArray objectAtIndex:0] type]]; //This should invoke the appropriate method stored in the pointer.
Right now the code above says (the very first block of code):
Lvalue required as unary '&' operand.
If you need any clarification just ask.
Also, just to let you know all the method I am calling are type void and don't have any parameters.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能仅使用
&
运算符从 Objective-C 函数中创建函数指针。您需要查看:
其中任何一个都可以做你想做的事。如果您不熟悉选择器(
@selector
编译器指令和SEL
类型),请务必阅读相关内容(这是您需要很多的基本概念)。块是相当新的(自 Mac OS X 10.6 和 iOS 4 起可用),它们将为您节省大量工作,而在早期版本的 Mac OS X 和 iOS 上,您需要目标/选择器、NSInvocation 或回调函数。You can't just make a function pointer out of an Objective-C function using the
&
Operator.You'll want to look into:
Any of these can do what you want. Definitely read about selectors (the
@selector
compiler directive and theSEL
type) if you're unfamiliar with that (it's a basic concept that you'll need a lot). Blocks are fairly new (available since Mac OS X 10.6 and iOS 4) and they'll save you a ton of work where you would have needed target/selector, NSInvocation or callback functions on earlier versions of Mac OS X and iOS.如果您需要传递对 C 函数的引用,请使用函数指针,但在使用 Objective-C 对象上的方法时,您应该真正使用 选择器 和
SEL
类型。您的代码将类似于:
Use function pointers if you need to pass around references to C functions but when working with methods on Objective-C objects you should really use selectors and the
SEL
type.Your code would then be something like: