我有包含自定義物件的 XIB,其中一個實際上是一個類集群,其-init方法總是回傳相同的單例物件。
基本上:
- (instancetype)init
{
self = [super init];
if (HelpLinkHelperSingleton==nil)
{
// This is the first instance of DDHelpLink: make it the immortal singleton
HelpLinkHelperSingleton = self;
}
else
{
// Not the first DDHelpLink object to be created: discard this instance
// and return a reference to the shared singleton
self = HelpLinkHelperSingleton;
}
return self;
}
從 macOS 12.0.1 開始,加載 XIB 會引發此例外:
This coder is expecting the replaced object 0x600002a4f680 to be returned from NSClassSwapper.initWithCoder instead of <DDHelpLink: 0x600002a487a0>
我嘗試實施<NSSecureCoding>并做同樣的事情,但這也不起作用。
還有一種方法可以在 NIB 中使用類簇嗎?
uj5u.com熱心網友回復:
我通過在 XIB 中使用一個代理物件將訊息轉發到單例來解決這個問題。
@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
如果我們將 fromNSProxy而不是子類化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
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/362495.html
上一篇:指向結構陣列的指標在輸入值時崩潰
