あなたの助けが必要です。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 バイトのポインターであることです。サイズが 140 バイトの UIButton オブジェクトを指す必要があります。しかし、実際には 1 バイトのデータを指します。'buttonWithType:' で初期化する必要がある UIButton オブジェクトはどうなりますか?
いくつかの回答を得た後に追加されました:
UIButton明確にするために:私はオブジェクトを取得したいのですが、このコードid pushButton5 = (id) result;の後、操作しようとするpushButton5とEXC_BAD_ACCESS. 誰かが私を助けることができますか?
これが原因で起こり得るのでしょうか?
Class cls = NSClassFromString(@"UIButton");
...
[anInvocationTMP setTarget:cls];
正しいですね。