【问题标题】:NSMutableArray with nested NSMutableDictionary or nested Subclasses带有嵌套 NSMutableDictionary 或嵌套子类的 NSMutableArray
【发布时间】:2015-05-28 22:01:10
【问题描述】:

我正在用 Swift 编写一个 iOS 应用程序,我正在使用 NSXMLParser 委托通过服务器端的 Rest API 解析来自服务器的 XML 数据。

我有以下数据结构:

<alarm>
      <rootcause> some properties... </rootcause>
      <symptoms>
             <symptom> some properties... </symptom>
             <symptom> some properties... </symptom>
      </symptoms>
  </alarm>

现在我正在将数据解析为一个 NSmutableArray,其中包含每个警报的 NSDictionary,其中包含每个 RootCause 的嵌套字典和带有症状的 NSMutableDictionary,其中包含每个症状的许多 NSDictionary 实例。

 1. NSMutableArray: alarms
    2. NSmutableDictionary: alarm
       3.NSMutabbleDictionary: rootcause
       3.NSMutableDictionary: symptoms
          4.NSMutableDictionary: symptom1
          4. NSMutableDictionary: symptom2
          .... 

当然这是一个有点复杂的数据模型,所以我的问题是我应该创建包含其他嵌套类的 NSObject 的子类并构建我的数据模型,还是应该保留嵌套 NSDictionaries 的数据结构。

或者将来管理数据模型更改和更好的调试等的最佳方法是什么。

【问题讨论】:

    标签: ios swift nsdictionary nsxmlparser nsmutabledictionary


    【解决方案1】:

    最好的方法是创建自己的数据结构,如下所示:

    class symptom
    {
       let yourValue = ""
       let someOtherValue = 0
    }
    
    class alarm
    {
       var rootcause = ""
       var symptoms:[symptom] = []
    
       //or if you have just a string
       var symptoms:[String] = []
    
    } 
    

    那么你要做的就是:

    var alarms:[alarm] = []
    
    for al in allAramsXML
    {
        let tmp = alarm()
        for sym in al.symptoms
        {
            let tmpSym = symptom()
            tmpSym.yourValue = ""
    
            tmp.symptoms.append(tmpSym)
        }
        alarms.append(tmp)
    }
    

    【讨论】:

    • 谢谢大家,我会试试这个,我会告诉你:)
    • 现在我在属性字典类型的字典中获取所有根本原因和症状属性:[NSObject:AnyObject]!如何循环并将这些值传递到 Rootcause 或 Symptom 的类属性中?
    • 你的意思是像 [rootcause : value]?
    • 是的,有没有更有效的方法来做到这一点?或者就像这样: self.currentAlarm.rootcause.alarmcount = attributeDict["alarmcount"] as String self.currentAlarm.rootcause.alarmid = attributeDict["alarmid"] as String
    【解决方案2】:

    转换它可以为您提供编译器验证,并且您不必乱用字符串键来获取您的数据。所以你应该做模型类,是的。

    一个例子可能如下所示:

    struct Symptom {
        let id : Int
        let description : String
    }
    
    struct Cause {
        let id : Int
    }
    
    struct Alarm {
        let rootCause : Cause
        let symptoms : [Symptom]
    }
    
    let alarms : [Alarm] = [Alarm(rootCause: Cause(id: 1), symptoms: [Symptom(id: 2, description: "some description")])]
    

    【讨论】:

    • 你能给我一些简单的例子吗?当我必须访问像 id 一样嵌套在内部的值时该怎么办?
    • 我添加了几行代码。访问它很容易:alarms[0].symptoms[0].description
    猜你喜欢
    • 2014-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-25
    • 2023-03-10
    • 2018-09-10
    相关资源
    最近更新 更多