You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将NSCoding解码的color和location重构为[[MapNode]]并重建nodeCollection?

解决方法

核心思路

要重建nodeCollection,需要将解码后的颜色数组和位置数组按对应层级一一配对,还原成[MapNode],再和对应的position组装成MapCollectionNode。

完整实现代码

// 假设解码后得到以下三个数组(根据你的实际解码变量名调整)
guard let positions = decodedPositions as? [CGPoint],
      let colorArrays = decodedColors as? [[UIColor]],
      let locationArrays = decodedLocations as? [[CGPoint]],
      // 校验三个数组的顶层长度一致
      positions.count == colorArrays.count,
      colorArrays.count == locationArrays.count else {
    // 处理数据不匹配的错误,比如打印日志或抛出异常
    return
}

var reconstructedNodeCollection: [MapCollectionNode] = []

for index in 0..<positions.count {
    let currentColors = colorArrays[index]
    let currentLocations = locationArrays[index]
    
    // 校验单组内的颜色和位置数量一致,避免崩溃
    guard currentColors.count == currentLocations.count else {
        print("第\(index)组数据中颜色与位置数量不匹配")
        continue
    }
    
    // 将颜色和位置配对成MapNode数组
    let containedNodes: [MapNode] = zip(currentColors, currentLocations).map { color, location in
        (color: color, location: location)
    }
    
    // 构建MapCollectionNode并加入结果数组
    let collectionNode = MapCollectionNode(position: positions[index], containedLocations: containedNodes)
    reconstructedNodeCollection.append(collectionNode)
}

self.nodeCollection = reconstructedNodeCollection

关键细节说明

  • 安全解包与校验:用guard替代原代码中的强制解包,同时校验数组长度一致性,避免因解码数据异常导致崩溃。
  • zip函数的使用:zip(currentColors, currentLocations)会将两个数组的对应元素配对成元组,再通过map转换成你需要的MapNode类型。
  • 层级对应:确保colorArrays和locationArrays是二维数组,每个子数组对应一个MapCollectionNode中的containedLocations集合。

内容的提问来源于stack exchange,提问作者Bob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 11:37:11