2015-10-24 124 views
1

我创建了User类,并给出了使用字典作为存储机制的建议,以使它更加灵活并满足我的需求。请参考questionSwift模型的最佳实践

这是我原来的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")任何表的模型任何表格。

如果我将模型名称更改为更广泛的范围,并将其重用于任何要从中抽取数据的表,我是否需要使用特定于模型的方法?

+0

我同意@duncanC,但如果您确实需要保留内部字典存储,您应该为各种属性创建离散计算属性并使用代码访问基础字典 – Paulw11

回答

5

我倾向于将自定义数据对象替换为字典。自定义数据对象具有特定的具体类型的命名字段。它是自我记录的,当你使用它时,你可以假设它具有你期望的属性,并且它们是正确的类型。用字典你不能假设(嗯,用Swift字典,你可以强制打字,但是你不能混合不同类型的属性,如姓名字符串和数字工资值)