为什么此代码给出EXC_BAD_ACCESS(使用IMP) [英] why does this code give EXC_BAD_ACCESS (using IMP)

查看:114
本文介绍了为什么此代码给出EXC_BAD_ACCESS(使用IMP)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码给我EXC_BAD_ACCESS,为什么?

This code gives me EXC_BAD_ACCESS, why?

NSMutableDictionary  *d = [[NSMutableDictionary alloc] init];
IMP imp= [d methodForSelector:@selector(setObject:forKey:) ];
imp(d,  @selector( setObject:forKey:), @"obj", @"key");

我刚开始使用IMP,请尝试.不知道为什么我也会收到错误消息,..过去,当我收到EXC_BAD_ACCESS消息时,该消息已打印在控制台上,这一次错误行将突出显示.

I'm just starting using IMP, firs try.. no luck. Not sure why I get the error, also.. in the past, when I got EXC_BAD_ACCESS, the message was printed at the console, this time the error line is highlighted.

一些注意事项: 启用了ARC,使用XCode 4.3.2,该项目使用Objective-C ++作为默认语言/编译器,此代码位于项目的开头

Some notes: ARC is enabled, XCode 4.3.2, the project uses Objective-C++ as de default language/compiler,this code is at the very beginning of the project

谢谢大家

推荐答案

您需要正确地转换函数指针,否则ARC不知道它应该在做什么. IMP是一个泛型函数指针,它接受一个id,一个选择器和可变数量的其他未定义参数,并返回一个id.您尝试调用的方法实现采用一个id,一个选择器以及紧随其后的两个id参数,并具有一个空返回类型.您可以通过更改为以下代码来对其进行修复:

You need to cast the function pointer properly or ARC doesn't know what it's supposed to be doing. IMP is a generic function pointer that takes an id, a selector and a variable number of other, undefined arguments and returns an id. The method implementation you're trying to call takes an id, a selector followed by exactly two id parameters and has a void return type. You can fix it by changing to the following code:

NSMutableDictionary* dict = [[NSMutableDictionary alloc] init];
void (*imp)(id, SEL, id, id) = (void(*)(id,SEL,id,id))[dict methodForSelector:@selector(setObject:forKey:)];
if( imp ) imp(dict, @selector(setObject:forKey:), @"obj", @"key");

在取消引用之前,应始终检查是否确实返回了函数指针,因为这也会导致崩溃.上面的代码即使在ARC环境中也可以使用.同样,即使您不使用ARC,也应始终将函数指针转换为实际的原型,而不是IMP.您永远不要使用IMP.其他可能导致重大问题的地方是该方法是否返回一个struct或该方法是否采用浮点参数等.

You should always check that you actually got a function pointer back before you dereference it, as that would also crash. The code above will work even in an ARC environment. Also, even when you're not using ARC, you should always cast your function pointers to the actual prototype rather than IMP. You should never use IMP. Other places that would cause major issues are if the method returns a struct or if the method takes floating point parameters, etc.

好习惯:如果发现函数指针语法不正确,请务必强制转换函数指针或为它们创建typedef.

Good habit: always cast your function pointers or make typedefs for them if you find the function pointer syntax jarring.

这篇关于为什么此代码给出EXC_BAD_ACCESS(使用IMP)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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