swift - 什么是 Swift 中的工厂类方法?

标签 swift initialization

我正在尝试构建一个需要安装 Couchbase-lite pod 的应用程序。当我尝试初始化一个类时,它说它是 NS_UNAVAILABLE,它告诉我改用工厂类方法。我如何使用“工厂类方法”以一般方式解决这个问题?

比如说我是这样做的:

class Polyline: CBLModel {

init() {        // the error starts here that says init is unavailable

    /* code here */

}

最佳答案

工厂方法是创建类实例的类函数。

Couchbase documentation says您应该遵循完全绕过 init 的模式:

Remember that every model has a one-to-one association with a document in the database. CBLModel has no public initializer methods, and you should not implement any yourself in subclasses.

创建新折线应按如下方式完成:

let poly = Polyline(forNewDocumentInDatabase: database)

如果需要自定义初始化,也需要进入工厂方法:

class Polyline : CBLModel {
    @NSManaged var x : Int
    @NSManaged var y : Int

    class func newPolylineInDatabase(database: CBLDatabase, withX x: Int andY y:Int)
    -> Polyline {
        let res = Polyline(forNewDocumentInDatabase: database)
        res.x = x
        res.y = y
        return res
    }
}

关于swift - 什么是 Swift 中的工厂类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36604812/

相关文章:

ios - DJI SDK 用户界面 : Customizing contentViewController in DULDefaultViewController

c# - C# 的 TripleDES IV?

c++ - 显式转换函数、直接初始化和转换构造函数

node.js - 如何使用本地文件中的数据一次性初始化 Node 模块

ios - 现在 Swift 是开源的,我可以在不是 Mac 的计算机上编写和编译 iOS 应用程序吗?

string - 在 Swift 中,NSAttributedString 的字符数比 String 多吗?

swift - 如果标签太长,我如何在结尾淡出而不是用 "..."替换结尾/如何使用 GoogleToolboxForMac

swift - Xcode:设置 UIControl 背景颜色在方向更改时重置

c++ - 使用带有 clang 的初始化列表初始化简单结构

c++ - 等号对大括号初始化有影响吗?例如。 'T a = {}' 与 'T a{}'