我经常需要缓存一个值,以便在类的多个实例中重用它,例如:
class Session {
typealias T = Session
let chatId: Int64
let userId: Int64
var name = ""
var url = ""
// ------- Define schema helpers --------
// The problem: access to them is dispatch_once-d.
static let table = Table("Session")
static let chatIdColumn = Expression<Int64>("ChatId")
static let userIdColumn = Expression<Int64>("UserId")
static let nameColumn = Expression<String>("Name")
static let urlColumn = Expression<String>("Url")
init() {
...
// ------ They're used in constructor: ------
guard let chat = db.pluckItem(T.table, T.chatIdColumn, chatId)
else { return }
userId = wish[T.userIdColumn]
name = wish[T.nameColumn]
url = wish[T.urlColumn]
}
func save() throws {
// ------ They're also used when saving the object back to DB ------
...
try db.upsert(T.table, T.wishIdColumn, wishId, setters:
T.userIdColumn <- userId,
T.nameColumn <- name,
T.urlColumn <- url
)
func other() {
// ------ Sometimes they're used in other methods of the class ------
}
}
静态和全局变量使用dispatch_once进行原子初始化,因此访问它们会产生一些开销。 (参见Jckarter对https://devforums.apple.com/thread/229436的答复)
有没有办法以非原子方式缓存值?在大多数情况下,我不需要线程安全,并且在类实现内部使用变量。
简单地声明非静态实例变量不是一个选项,因为计算的值可能很昂贵,或者在每个类实例中存储的值太大。
当然,我可以为这些共享属性创建一个单独的类,并在EACH对象的成员变量中存储对它的引用,但这会不必要地使实现复杂化并增加内存开销。