我有一个正在迭代并寻找特定标志的数组。如果标志值为 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/