在Objective-C中,这适用于Singleton in Interface Builder
static Universe *instance;
+ (Universe *)instance {
return instance;
}
+ (id)hiddenAlloc {
return [super alloc];
}
+ (id)alloc {
return [self instance];
}
+ (void)initialize {
static BOOL initialized = NO;
if (!initialized) {
initialized = YES;
instance = [[Universe hiddenAlloc] init];
}
}
由于覆盖了分配,IB会选择Universe
的唯一实例
这在Swift中可行吗? [我已经遇到了我的解决方案,即here on Github。]
答案 0 :(得分:0)
这是一个开始(我认为)。 Objective-C中的超类。
请在Github上查看...有任何帮助表示赞赏!
Singleton.h(必须在Bridging Header中)
#import <Foundation/Foundation.h>
@interface Singleton : NSObject
+ (Singleton *)instance;
@end
<强> Singleton.m 强>
#import "Singleton.h"
@implementation Singleton
static Singleton *instance;
+ (Singleton *)instance {
return instance;
}
+ (id)hiddenAlloc {
return [super alloc];
}
+ (id)alloc {
return [self instance];
}
+ (void)initialize {
static BOOL initialized = NO;
if (!initialized) {
initialized = YES;
instance = [[self hiddenAlloc] init];
}
}
@end
<强> Universe.swift 强>
import UIKit
// MARK: - convenience access
let universe = Universe.sharedInstance
@objc(Universe)
class Universe : Singleton {
static let sharedInstance = Universe()
override class func instance() -> Singleton {
return sharedInstance
}
}
Universe
对象始终显示相同的哈希值(和内存地址),但它没有保留其IBOutlet
个变量...所以这仍然100%被打破,但它起步(可能)。