我需要你的帮助。我对 NSInvocation 'getReturnValue:' 方法有一些问题。我想以编程方式创建 UIButton,甚至更多,我想使用 NSInvocation 并通过 NSArray 传递值来动态创建它(这就是我包装 UIButtonTypeRoundedRect 的原因)。
清单。
NSLog(@"Button 4 pushed\n");//this code executed when button pushed
Class cls = NSClassFromString(@"UIButton");//if exists {define class},else cls=nil
SEL msel = @selector(buttonWithType:);
//id pushButton5 = [cls performSelector:msel withObject:UIButtonTypeRoundedRect];//this code works correctly,but I want to do this by NSInvocation
//---------------------------
NSMethodSignature *msignatureTMP;
NSInvocation *anInvocationTMP;
msignatureTMP = [cls methodSignatureForSelector:msel];
anInvocationTMP = [NSInvocation invocationWithMethodSignature:msignatureTMP];
[anInvocationTMP setTarget:cls];
[anInvocationTMP setSelector:msel];
UIButtonType uibt_ = UIButtonTypeRoundedRect;
NSNumber *uibt = [NSNumber numberWithUnsignedInt:uibt_];
NSArray *paramsTMP;
paramsTMP= [NSArray arrayWithObjects:uibt,nil];
id currentValTMP = [paramsTMP objectAtIndex:0];//getParam from NSArray
NSInteger i=2;
void* bufferTMP;
//if kind of NSValue unwrapp it.
if ([currentValTMP isKindOfClass:[NSValue class]]) {
NSUInteger bufferSize = 0;
NSGetSizeAndAlignment([currentValTMP objCType], &bufferSize, NULL);
bufferTMP = malloc(bufferSize);
[currentValTMP getValue:bufferTMP];//copy currentVal to bufer
[anInvocationTMP setArgument:bufferTMP atIndex:i];// The +2 represents the (self) and (cmd) offsets
}else {
[anInvocationTMP setArgument:¤tValTMP atIndex:i];//Again,+2 represents (self) and (cmd) offsets
}
void* result = malloc([[cls methodSignatureForSelector:msel] methodReturnLength]);
[anInvocationTMP invoke];
[anInvocationTMP getReturnValue:result];
NSLog(@"sizeof(UIButton)=%i,sizeof(result)=%i,methodreturnlength = %i,sizeof(*result)=%i",class_getInstanceSize(NSClassFromString(@"UIButton")),sizeof(result),[[cls methodSignatureForSelector:msel] methodReturnLength],sizeof(*result));
id pushButton5;
pushButton5=result;
//---------------------------
NSLog 输出:sizeof(UIButton)=140,sizeof(result)=4,methodreturnlength = 4,sizeof(*result)=1
问题是来自 NSInvocation 的值是大小为 4 字节的指针。它应该指向 UIButton 对象,大小为 140 字节。但实际上是指1个字节的数据。那么 UIButton 对象会发生什么,应该由 'buttonWithType:' 初始化?
得到一些答案后添加:
澄清一下:我想得到UIButton
对象,但是在这段代码之后id pushButton5 = (id) result;
,当我尝试使用它时pushButton5
,它会导致EXC_BAD_ACCESS
. 有人能帮我吗?
会因为这个而发生吗?
Class cls = NSClassFromString(@"UIButton");
...
[anInvocationTMP setTarget:cls];
这是正确的,不是吗?