[英]How to create an NSInvocation object using a method that takes a pointer to an object as an argument
[英]How to create instance of my own class using NSInvocation?
我試圖動態創建自定義類的新實例(自定義init
方法調用,帶有BOOL
參數)。 如何使用NSInvocation
做到這一點?
這是我到目前為止的內容:
NSMethodSignature* signature = [NSClassFromString(className) instanceMethodSignatureForSelector: sel];
NSInvocation* invocation = [NSInvocation invocationWithMethodSignature: signature];
[invocation setTarget: [NSClassFromString(className) alloc]];
[invocation setSelector:sel];
[invocation setArgument:&value atIndex:2];
[invocation invoke];
[invocation getReturnValue:&obj];
上面的示例在[invocation invoke];
行中引發錯誤[invocation invoke];
錯誤是"message sent to deallocated instance"
。
您的代碼無法正常工作,因為NSInvocation
不會保留目標或任何參數,除非您告知目標對象或參數(帶有retainArguments
)。 因此,您alloc
一個實例,然后在invoke
NSInvocation
之前將其銷毀。
或者,創建一個實例變量,並將alloc
實例存儲在那里,然后將其傳遞給NSInvocation
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.