gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 08:40:36 25 4
gpt4 key购买 nike

我正在尝试构建一个需要安装 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com