我在前进的工作上遇到了麻烦。由于某种原因,Objective-C运行时完全忽略了我的forwardInvocation:方法,并抛出了无法识别的选择器异常。

我的测试代码如下:

@interface InvocationTest : NSObject
{
}

+ (void) runTest;

@end


@interface FullClass: NSObject
{
    int value;
}
@property(readwrite,assign) int value;

@end

@implementation FullClass

@synthesize value;

@end


@interface SparseClass: NSObject
{
}

@end

@implementation SparseClass

- (void)forwardInvocation:(NSInvocation *)forwardedInvocation
{
    NSLog(@"ForawrdInvocation called");

    FullClass* proxy = [[[FullClass alloc] init] autorelease];
    proxy.value = 42;
    [forwardedInvocation invokeWithTarget:proxy];
}

@end


@implementation InvocationTest

+ (void) runTest
{
    SparseClass* sparse = [[[SparseClass alloc] init] autorelease];
    NSLog(@"Value = %d", [sparse value]);
}

@end

我正在处理来自以下资源的信息:

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtForwarding.html#//apple_ref/doc/uid/TP40008048-CH105
http://cocoawithlove.com/2008/03/construct-nsinvocation-for-any-message.html

据我所知,当我调用[sparse value]时,运行时应该在SparseClass实例上调用forwardInvocation :,但它会被完全忽略:

最佳答案

您还必须重写- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector才能使其正常工作。

我猜

- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
    return [FullClass instanceMethodSignatureForSelector:aSelector];
}

应该可以。

10-08 12:10