ios - Swift 中的 dispatch_once 单例

标签 ios swift singleton grand-central-dispatch

我需要将以下 Objective-C 代码转换为 Swift。

static RWBasicCell *sizingCell = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
  sizingCell = [self.tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"];
});

我该怎么做?我用 Google 搜索并找到了这个例子。

class SingletonC {

    class var sharedInstance : SingletonC {
        struct Static {
            static var onceToken : dispatch_once_t = 0
            static var instance : SingletonC? = nil
        }
        dispatch_once(&Static.onceToken) {
            Static.instance = SingletonC()
        }
        return Static.instance!
    }
}

但它是为了返回一个类的单个。

最佳答案

这是来自 this Ray Wenderlich tutorial , 正确的? Swift 没有可以作用域为函数的静态变量,但是您可以在函数中嵌套一个类型,并给它静态变量。这是该方法开始的 Swift 等效版本:

func heightForBasicCellAtIndexPath(indexPath: NSIndexPath) -> CGFloat {
    struct Static {
        static var sizingCell: RWBasicCell?
    }

    if Static.sizingCell == nil {
        Static.sizingCell = tableView.dequeueReusableCellWithIdentifier(RWBasicCellIdentifier) as RWBasicCell
    }

    // ...
}

关于ios - Swift 中的 dispatch_once 单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27486600/

相关文章:

ios - 找出光标何时移动(UITextView)

ios - 由于 NSUnknownKeyException,无法从 RestKit 存储核心数据

ios - 如何使用 scrollViewWillEndDragging :withVelocity:targetContentOffset to ensure only stops scrolling at two possible positions?

ios - 我的 TableViewController 卡住了(初学者)

c++ - 如何删除单例指针?

swift - 创建通用单例

jakarta-ee - 使用 Java EE BeanManager 作为单例

iOS Swift Paypal 集成崩溃并出现 NSInvalidArgumentException 应用程序尝试在目标上呈现 nil 模态视图 Controller

ios - 如何在 Swift 中用较少重复的代码进行连续的方法调用?

swift - 设备方向更改后使 collectionViewCell 中的 CAShapeLayer 无效并重绘