1
我创建了User
类,并给出了使用字典作为存储机制的建议,以使它更加灵活并满足我的需求。请参考question。Swift模型的最佳实践
这是我原来的User
型号:
下面是使用字典作为存储机制,我更新User
类:
final class User: NSObject, ResponseObjectSerializable, ResponseCollectionSerializable {
var properties = NSDictionary()
init?(response: NSHTTPURLResponse, representation: AnyObject) {
if let dataRepresentation = ((representation as! NSDictionary).valueForKey("data") as? [String: AnyObject]) {
properties = dataRepresentation
}
properties = representation as! NSDictionary
}
static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [User] {
var users: [User] = []
if let dataRepresentation = ((representation as! NSDictionary).valueForKey("data") as? [NSDictionary]) {
if let dataRepresentation = dataRepresentation as? [[String: AnyObject]] {
for userRepresentation in dataRepresentation {
if let user = User(response: response, representation: userRepresentation) {
users.append(user)
}
}
}
}
return users
}
}
想到的,虽然这个问题,是如何将另一位程序员知道他可以从User
模型中获取哪些字段,因为我不再将它们单独存储为变量。他们只需要检查数据库并查看表格的结构?
另外,User
类是设置现在的样子,它几乎可能是我从数据库中提取(因为我有它现在没有User
模型具体方法),我可以随时调用user.properties.valueForKeyPath("column_name")
任何表的模型任何表格。
如果我将模型名称更改为更广泛的范围,并将其重用于任何要从中抽取数据的表,我是否需要使用特定于模型的方法?
我同意@duncanC,但如果您确实需要保留内部字典存储,您应该为各种属性创建离散计算属性并使用代码访问基础字典 – Paulw11