【发布时间】:2011-08-12 07:03:56
【问题描述】:
我尝试将 CGRect 传递给 NSInvocation (setArgument:atIndex:)。我用 NSValue 包装它,推送到 NSArry,然后从 NSArray 获取并使用 NSValue (getValue:)。 (getValue:) 方法的调用导致之前声明的索引 NSInteger i 发生变化。谁能说说为什么会这样?
NSString className = @"UIButton";
Class cls = NSClassFromString(className);
cls pushButton5 = [[cls alloc] init];
CGRect rect =CGRectMake(20,220,280,30);
NSMethodSignature *msignature1;
NSInvocation *anInvocation1;
msignature1 = [pushButton5 methodSignatureForSelector:@selector(setFrame:)];
anInvocation1 = [NSInvocation invocationWithMethodSignature:msignature1];
[anInvocation1 setTarget:pushButton5];
[anInvocation1 setSelector:@selector(setFrame:)];
NSValue* rectValue = [NSValue valueWithCGRect:rect];
NSArray *params1;
params1= [NSArray arrayWithObjects:rectValue,nil];
id currentVal = [params1 objectAtIndex:0];
NSInteger i=2;
if ([currentVal isKindOfClass:[NSValue class]]) {
void *bufferForValue;
[currentVal getValue:&bufferForValue];
[anInvocation1 setArgument:&bufferForValue atIndex:i];
}else {
[anInvocation1 setArgument:¤tVal atIndex:i];
}
[anInvocation1 invoke];
当 this(getValue:) 方法实现 'i' 的值从 2 更改为:1130102784 时,在(setArgument:atIndex:) 中我有一个 SIGABRT,因为索引 i 超出范围。
那么为什么[NSValue getValue:(*void) buffer]会改变其他变量呢?
(P.S. 我是在函数中做的,所以我简化了一个例子并直接初始化数组。 如果我直接设置atIndex:2,它就完美了。但是我很伤心我简化了一点,我需要将i传递给atIndex :)
感谢 Tom Dalling(特别是)并解决了 sergio 问题。我删除了这个:
void *bufferForValue;
[currentVal getValue:&bufferForValue];
[anInvocation1 setArgument:&bufferForValue atIndex:i];
然后粘贴
NSUInteger bufferSize = 0;
NSGetSizeAndAlignment([currentVal objCType], &bufferSize, NULL);
void* buffer = malloc(bufferSize);
[currentVal getValue:buffer];
[anInvocation1 setArgument:buffer atIndex:i];
谢谢。 Stackoverflow.com 对聪明人很有帮助的网站。
【问题讨论】: