我通过在XIB中使用一个代理对象来解决这个问题,该代理对象将消息转发给singleton。
@interface HelpLinkHelperProxy : NSObject
@end
@implementation HelpLinkHelperProxy
{
HelpLinkHelper* _singleton;
}
- (void) forwardInvocation:(NSInvocation*)invocation
{
if (_singleton == nil)
{
_singleton = [HelpLinkHelper new];
}
if ([_singleton respondsToSelector:[invocation selector]])
{
[invocation invokeWithTarget:_singleton];
}
else
{
[super forwardInvocation:invocation];
}
}
@end
如果我们从
NSProxy
而不是
NSObject
,解决方案如下所示:
@interface HelpLinkHelperProxy : NSProxy
@end
@implementation HelpLinkHelperProxy
{
HelpLinkHelper* _singleton;
}
- (instancetype) init
{
_singleton = [HelpLinkHelper new];
return self;
}
- (NSMethodSignature*) methodSignatureForSelector:(SEL)sel
{
return [_singleton methodSignatureForSelector:sel];
}
- (void) forwardInvocation:(NSInvocation*)invocation
{
if ([_singleton respondsToSelector:[invocation selector]])
{
[invocation invokeWithTarget:_singleton];
}
else
{
[super forwardInvocation:invocation];
}
}
+ (BOOL) respondsToSelector:(SEL)aSelector
{
return [HelpLinkHelper respondsToSelector:aSelector];
}
@end