我有一个数组,我正在迭代它并寻找一个特定的标志。如果标志值为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的方法时,我可以看到for循环中的NSLog输出了预期的NSArray结果,但是它崩溃了,并显示了错误消息EXC_BAD_ACCESS。
即使NSInvocation返回正确的结果,我也不能理解为什么它会失败。如果没有NSInvocation,for循环就不会崩溃。
任何建议都会很有帮助。
谢谢
发布于 2014-02-26 15:00:04
我猜你是在用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;
发布于 2020-03-01 21:48:08
这是您不知道返回值类型的情况下的解决方案
__weak id weakReturnValue;
[_invocation getReturnValue:&weakReturnValue];
id returnValue = weakReturnValue; // ARC owned strong reference
https://stackoverflow.com/questions/22018272
复制相似问题