ios - 如何在类扩展中添加静态(存储)属性以创建单例? ( swift )

标签 ios objective-c swift extension-methods

我想将这段代码转换成 Swift。这里的 Objective-C 代码正在创建一个单例对象(如果我可以这样描述的话)。我可以使用 dispatch_once_t 来转换它,但我想使用一种更优雅的方式,应该类似于“static let bundle: NSBundle!”。但是“static let bundle: NSBundle!”在扩展中是不允许的,因为它不允许存储属性。

那么是否可以不用dispatch_once_t来转换代码呢?

我遇到了一个问题,我不能在类扩展中存储属性

@implementation NSBundle (CTFeedback)

+ (NSBundle *)feedbackBundle
{
    static NSBundle *bundle = nil;
    static dispatch_once_t predicate;

    dispatch_once(&predicate, ^{
        NSBundle *classBundle = [NSBundle bundleForClass:[CTFeedbackViewController class]];
        NSURL *bundleURL = [classBundle URLForResource:@"CTFeedback" withExtension:@"bundle"];

        if (bundleURL) {
            bundle = [NSBundle bundleWithURL:bundleURL];
        } else {
            bundle = [NSBundle mainBundle];
        }
    });

    return bundle;
}

@end

我的 Swift 代码:

extension NSBundle
{
    static func feedbackBundle()-> NSBundle
    {
        static let bundle: NSBundle! //!! **Compiler Error here**

        let classBundle = NSBundle.init(forClass: CTFeedbackViewController.self)
        let bundleURL = classBundle.URLForResource("CTFeedback", withExtension: "bundle")

        if let bundleURL2 = bundleURL
        {
            bundle = NSBundle(URL: bundleURL2)
        }
        else
        {
            bundle = NSBundle.mainBundle()
        }

        return bundle;
    }
}

更新:

感谢大家的回答。我现在就是这样做的。我不确定这是最好的方法/

private class FeedbackBundle
{
    static let classBundle = NSBundle.init(forClass: CTFeedbackViewController.self)
}

extension NSBundle
{
    static func feedbackBundle()-> NSBundle
    {
        let bundleURL = FeedbackBundle.classBundle.URLForResource("CTFeedback", withExtension: "bundle")
        if let bundleURL2 = bundleURL
        {
            return NSBundle(URL: bundleURL2)!
        }
        else
        {
            return NSBundle.mainBundle()
        }
    }
}

最佳答案

在 Swift 中,您不能在扩展中添加静态变量。 如果可以的话,您可以在原来的类(class)重试。否则,您可以像这样修改代码:

if let bundleURL2 = bundleURL
{
    return NSBundle(URL: bundleURL2)
}
else
{
    return NSBundle.mainBundle()
}

关于ios - 如何在类扩展中添加静态(存储)属性以创建单例? ( swift ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38863358/

相关文章:

objective-c - 保存用户名并通过 Objective C iPhone

ios - 如何使用 dequeueReusableCellWithIdentifier 快速管理 UITableView 中的购物车?

ios - 如何将 .xcworkspace 添加到 .xcodeprodj

ios - 如何启动并运行带有 MagicalRecord(核心数据)的 iCloud?

ios - 与应用程序中只有 1 个屏幕的横向模式相关的问题

ios - 检测核心数据的删除

ios - 在文本字段中定位文本

ios - 如何使用 RestKit 将嵌套的 JSON 对象存储到核心数据中

swift - 在 Swift 中使用 CocoaLumberJack 时的细粒度日志记录

iOS 钥匙串(keychain) - LAContext.setCredential(data, .applicationPassword) 在模拟器上返回 false