为什么此代码给出EXC

编程入门 行业动态 更新时间:2024-10-26 08:35:29
本文介绍了为什么此代码给出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

本文发布于:2023-10-07 14:43:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1469669.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:代码   EXC

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!