我無法讓forwardInvocation正常工作。出於某種原因,Objective-C運行時完全忽略了我的forwardInvocation:方法並引發了無法識別的選擇器異常。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]時調用forwardInvocation:在SparseClass的實例上,但它被完全忽略:
- [SparseClass值]:無法識別的選擇發送到實例0x4b1c4a0 ***終止應用程序由於未捕獲的異常 'NSInvalidArgumentException',原因: ' - [SparseClass值]:無法識別的選擇發送到實例0x4b1c4a0'
太棒了!像魅力一樣工作。 – Karl 2011-01-07 01:09:46