在Interface Builder中使用Singleton和Swift

时间:2016-06-08 19:41:47

标签: swift interface-builder

在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。]

1 个答案:

答案 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%被打破,但它起步(可能)。