gpt4 book ai didi

objective-c - NSInvocation 无参数

转载 作者:太空狗 更新时间:2023-10-30 03:31:55 29 4
gpt4 key购买 nike

我如何(或什至可以)将 nil 参数传递给 NSInvocation 对象?

我试着这样做:

NSMethodSignature* signature = [AClass instanceMethodSignatureForSelector:@selector(aMethod:theOtherArg:)];
NSInvocation* invocation = [NSInvocation invocationWithMethodSignature: signature];

[invocation setTarget: aTargetObj];
[invocation setSelector: @selector(aMethod:theOtherArg:)];

/* I've tried both this way */
AnObj* arg1 = nil;
AnotherObj* arg2 = nil;
[invocation setArgument: &arg1 atIndex:2];
[invocation setArgument: &arg2 atIndex:3];

/* and this way */
//[invocation setArgument: nil atIndex:2];
//[invocation setArgument: nil atIndex:3];

NSInvocationOperation* operation = [[NSInvocationOperation alloc] initWithInvocation:invocation];
//opQueue is an NSOperationQueue object
[opQueue addOperation:operation];

第一种方法将崩溃并显示此消息:

Thread 0 Crashed:
0 libSystem.B.dylib 0x927c1f10 strlen + 16
1 com.apple.CoreFoundation 0x92dd1654 __NSI3 + 500
2 com.apple.CoreFoundation 0x92dd1994 -[NSInvocation retainArguments] + 132
3 com.apple.Foundation 0x96a50c5e -[NSInvocationOperation initWithInvocation:] + 78

第二种方法将崩溃并显示此消息:

Error: Exiting due to caught object *** -[NSInvocation setArgument:atIndex:]: NULL address argument

在此先感谢您的帮助!

最佳答案

是的,你可以传递 nil 参数。更准确地说,您可以传递一个内容为 nil 的有效指针。

我无法重现您的特定问题。这是我用来测试它的代码。您的程序中可能有其他原因导致了错误。

#import <Foundation/Foundation.h>

@interface Person : NSObject {
NSString *name;
NSUInteger age;
}
- (void)setName:(NSString *)personName age:(NSNumber *)personAge;
@end

@implementation Person
- (void)setName:(NSString *)personName age:(NSNumber *)personAge {
NSLog(@"setName:%@ age:%@", personName, personAge);
name = [personName copy];
age = [personAge unsignedIntegerValue];
}
@end

int main() {
NSAutoreleasePool *pool = [NSAutoreleasePool new];
Person *person = [Person new];

SEL sel = @selector(setName:age:);

NSMethodSignature *sig = [Person instanceMethodSignatureForSelector:sel];
NSInvocation *inv = [NSInvocation invocationWithMethodSignature:sig];

[inv setTarget:person];
[inv setSelector:sel];

NSString *name = nil;
NSNumber *age = nil;

[inv setArgument:&name atIndex:2];
[inv setArgument:&age atIndex:3];

// [inv retainArguments];
// [inv invoke];

NSInvocationOperation *op = [[[NSInvocationOperation alloc] initWithInvocation:inv] autorelease];
NSOperationQueue *queue = [NSOperationQueue new];
[queue addOperation:op];

[pool release];
return 0;
}

我还在不使用 NSInvocationOperation 和直接发送 -retainArguments 的情况下对其进行了测试,因为这似乎是触发错误的原因。

郑重声明,您的第二种方法将不起作用,因为 -[NSInvocation setArgument:atIndex:] 需要指向将被复制的缓冲区的有效内存地址。对于对象参数,缓冲区必须包含对象的地址。对象的地址可以为零,但缓冲区的地址必须有效。

关于objective-c - NSInvocation 无参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4555489/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com