Home  >  Q&A  >  body text

ios - swift 如何创建模型返回给cell?



我解析json 存放 和方式 总感觉怪怪的 不是最好的办法,我看到网上说可以用模型去返回cell
但是怎么应该怎么写这个模型???

举例用 table_name table_num 应该怎么创建模型 和返回到cell上面?? 希望得到解答。。。

PHP中文网PHP中文网2741 days ago652

reply all(3)I'll reply

  • 怪我咯

    怪我咯2017-04-17 17:42:42

    JSON->Dictionary->Model?

    1. Take a look at the data returned by json. It is recommended that you use AFN to request. The returned data response is an object dictionary or array, because json is generally packaged into an array (the array is also a dictionary in fact) or a dictionary. You can Go to json.cn to directly see the detailed structure of the returned data
    2. Set a model. The attribute names required to be defined in the model are the same as the key values ​​​​of the dictionary because kvc is used to directly convert the dictionary to the model

    Definition and assignment of simple models:

    Model definition
    `import UIKit

    class UserInfo: NSObject {

    var screen_name:String?
    
    var profile_image_url:String?
    
    var verified: Int = -1
    
    var mbrank: Int = 0
    
    // kvc 遍历赋值
    init(dict:[String:AnyObject]) {
        
        super.init()
    
        setValuesForKeysWithDictionary(dict)
        
    }
    // 防止未定义属性未赋值报错
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    

    }`

    If you want to assign a value, just take the attributes of the instantiated model and assign it to the cell when it needs it

    Supplement: In this way, the data source is an array and stores multiple sets of data you need at the same time

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 17:42:42

    Reflection~ Json -> Object
    Then you can play whatever you want~

    reply
    0
  • 阿神

    阿神2017-04-17 17:42:42

    Don’t use models to return cells. One is the model and the other is the view. The two should be separated as much as possible. You are doing the right thing. But it is best to make a table_nameAndIdArray. Each element of this array is a name and id (you can use tuple, struct or class).

    reply
    0
  • Cancelreply