ios - NSInvocation 返回值但使用 EXC_BAD_ACCESS 使应用程序崩溃

标签 ios objective-c nsinvocation

我有一个正在迭代并寻找特定标志的数组。如果标志值为 nil,我将调用一个生成调用对象并返回调用结果的方法。

我的代码结构如下

for(NSString *key in [taxiPlanes allKeys])
{
        Plane *currentPlane = [taxiPlanes objectForKey:key];

        if(currentPlane.currentAction == nil)
        {
            NSString *selector = [[currentPlane planeTakeoffSequence] firstObject];
            currentPlane.currentAction = selector;

            // Calling for NSInvocation in [self ...]
            NSArray *action = [NSArray arrayWithArray:[self operationFromTakeoffAction:currentPlane.currentAction AtPoint:currentPlane.position]];

        NSLog(@"%@",action);
        }
 }

生成NSInvocation的方法

-(NSArray *) operationFromTakeoffAction:(NSString *) action AtPoint:(CGPoint) flightPoint
{
    NSMethodSignature *methodSignature = [FlightOperations instanceMethodSignatureForSelector:NSSelectorFromString(action)];
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature];

    [invocation setTarget:fOps];
    [invocation setSelector:NSSelectorFromString(action)];
    [invocation setArgument:&flightPoint atIndex:2];

    NSArray *resultSet = [NSArray alloc]init];
    [invocation invoke];
    [invocation getReturnValue:&resultSet];

    return resultSet;
}

在 for 循环中,没有 NSInvocation ([self ....]) 的方法调用,循环执行得很好,没有崩溃。但是当我引入调用 NSInvocation 的方法时,我能够看到 NSLog in for 循环打印预期的 NSArray 结果,但它崩溃并显示错误消息 EXC_BAD_ACCESS。

即使 NSInvocation 返回正确的结果,我也无法弄清楚为什么它会失败。没有 NSInvocation,for 循环不会崩溃。

任何建议都会有所帮助。

谢谢

最佳答案

我猜你正在使用 ARC?

问题出在 [invocation getReturnValue:&resultSet]; 行。 getReturnValue: 只是将返回值的字节复制到给定的内存缓冲区中,而不考虑类型。如果返回类型是可保留的对象指针类型,它不知道也不关心内存管理。由于 resultSet 是一个对象指针类型的 __strong 变量,ARC 假设任何已经放入该变量的值都被保留,因此当它出去时将释放它的范围。在这种情况下情况并非如此,因此它崩溃了。 (此外,您让 resultSet 最初指向的数组将被泄漏,因为 getReturnValue: 会在不释放它的情况下覆盖该值。为什么您甚至使该变量指向一个对象首先超出了我的范围。)

解决方案是必须将指向非保留类型的指针提供给getReturnValue:。要么:

NSArray * __unsafe_unretained tempResultSet;
[invocation getReturnValue:&tempResultSet];
NSArray *resultSet = tempResultSet;

或:

void *tempResultSet;
[invocation getReturnValue:&tempResultSet];
NSArray *resultSet = (__bridge NSArray *)tempResultSet;

关于ios - NSInvocation 返回值但使用 EXC_BAD_ACCESS 使应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22018272/

相关文章:

ios - 在 ios 中使用 Collection View 创建 View

ios - 如何在 Apple Watch 上编辑顶部状态栏?

ios - 确定来自 NSInvocation getArgument 的 (void *) 指针是对象还是原语

ios - @selector 的多个参数

ios - 如何将由 NE 和 SW 坐标组成的特定边界拟合到可见 map View 中?

ios - 有没有ios cloudkit界面的插件

iphone - 如何在运行时设置 Segue 标识符(以编程方式)?

ios - WKWebView 显示灰色背景并且 pdf 内容在 viewcontroller 开关上变得不可见

iOS/Objective-C 元类和类别