gpt4 book ai didi

swift - Swift 中数据模型的动态属性(getters/setters)

转载 作者:行者123 更新时间:2023-11-28 13:00:59 25 4
gpt4 key购买 nike

我正在尝试使用 Swift(我是新手)为我的数据模型创建一个干净的界面。这些模型由 Firebase 支持(尽管这最终与实际问题无关)。我想避免的是一遍又一遍地编写大量的 setter/accessor 样板代码。

例如:

class MyData {
let connection: Firebase!

private var _name: String? // internal storage, like an iVar in ObjC

init(connection: Firebase!) {
self.connection = connection
self.connection.observeEventType(.Value, withBlock: { snapshot in
_name = snapshot["name"]
}
}

var name: {
get {
return _name
}
set(name) {
// When the client sets the name, write it to Firebase
_name = name
self.connection.childByAppendingPath("name").setValue(name)
}
}
}

我确信我在那里犯了很多错误。这个想法是在实例化时首先从服务器加载数据。随后,我们可以调用 my_data_instance.name 来获取该名称,或者 my_data_instance.name = "foo" 并且该名称将自动写入服务器。

单个属性需要大约 10 行代码(其中会有很多)。疯了!一定有更好的方法!


编辑:明确地说,我想避免编写尽可能多的样板代码。考虑像 Mantle 这样的库,其中仅定义一个 @property 就足以做你想做的一切。在我看来,如果不止一行代码说 I have an attribute called "name", handle it via Firebase 就过于冗长了。

最佳答案

您可以使用 Key-Value Observing监控您的属性的变化。更多信息在 Adopting Cocoa Design Patterns in Swift .

import Foundation

private var KVOContext = 0

// Your class must inherit from NSObject
class MyData : NSObject {
private let propertiesToObserve = ["name", "location"]

dynamic var name: String
dynamic var location: String

init(name: String, location: String) {
self.name = name
self.location = location
super.init()

// Add the properties that you want to observe
for property in self.propertiesToObserve {
self.addObserver(self, forKeyPath: property, options: [.New, .Old], context: &KVOContext)
}
}

// This method is called whenever an observed property is changed
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if let property = keyPath,
newValue = change![NSKeyValueChangeNewKey],
oldValue = change![NSKeyValueChangeOldKey] {
print("\(property) changed from \(oldValue) to \(newValue)")
// If oldValue != newValue, write back to Firebase
}
}

// Remove self as observer of self
deinit {
for property in self.propertiesToObserve {
self.removeObserver(self, forKeyPath: property)
}
}
}

let data = MyData(name: "John", location: "Chicago")
data.name = "David" // print: name changed from John to David
data.location = "New York" // print: location changed from Chicago to New York

关于swift - Swift 中数据模型的动态属性(getters/setters),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33847054/

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