gpt4 book ai didi

ios - 在 swift 2 中从 plist 读取时无法创建 NSDictionary

转载 作者:行者123 更新时间:2023-11-29 01:14:17 24 4
gpt4 key购买 nike

我正在尝试从 plist 中读取信息,( PetList.plist ) 但我不知道为什么失败了。变量路径是正确的,但是 myDict 是 nil,else 部分被执行。我想要做的是从 plist 加载信息,然后将值分配给 pets 数组。
var pets = 宠物 func loadGameData() {

    let path = NSBundle.mainBundle().pathForResource("PetList", ofType: "plist")

let myDict = NSDictionary(contentsOfFile: path!)

if let dict = myDict {
//loading values
for i in 0..<pets.count {
pets[i].petName = dict.objectForKey("petName")!.absoluteString!
pets[i].health = dict.objectForKey("health")!.absoluteString!
pets[i].experience = dict.objectForKey("experience")!.absoluteString!
pets[i].hungry = dict.objectForKey("hungry")!.absoluteString!
pets[i].energy = dict.objectForKey("energy")!.absoluteString!
pets[i].level = dict.objectForKey("level")!.absoluteString!
pets[i].status = dict.objectForKey("status")!.absoluteString!
pets[i].searchKey = dict.objectForKey("searchKey")!.absoluteString!
pets[i].cleanliness = dict.objectForKey("cleanliness")!.absoluteString!
pets[i].isChoosed = dict.objectForKey("isChoosed")!.absoluteString!
pets[i].skill = dict.objectForKey("skill")!.absoluteString!
pets[i].imageName = dict.objectForKey("imageName")!.absoluteString!
}
} else {
print("WARNING: Couldn't create dictionary from PetList.plist! Default values will be used!")
}
}

最佳答案

有几个问题。

  • 顶级对象是一个数组
  • absoluteString 会导致编译错误。
  • 必须有一个 Pet 结构或类才能从数组创建实例。

像这样

struct Pet {
var petName = "", health = "", experience = "", hungry = ""
var energy = "", level = "", status = "", searchKey = ""
var cleanliness = "", isChoosed = "", skill = "", imageName = ""
}

var pets = [Pet]()

func loadGameData() {

let path = NSBundle.mainBundle().pathForResource("PetList", ofType: "plist")
if let myArray = NSArray(contentsOfFile: path!) as? [[String:String]] {
//loading values

for anItem in myArray {
var pet = Pet()
pet.petName = anItem["petName"]!
pet.health = anItem["health"]!
pet.experience = anItem["experience"]!
pet.hungry = anItem["hungry"]!
pet.energy = anItem["energy"]!
pet.level = anItem["level"]!
pet.status = anItem["status"]!
pet.searchKey = anItem["searchKey"]!
pet.cleanliness = anItem["cleanliness"]!
pet.isChoosed = anItem["isChoosed"]!
pet.skill = anItem["skill"]!
pet.imageName = anItem["imageName"]!
pets.append(pet)
}
} else {
print("WARNING: Couldn't create array from PetList.plist! Default values will be used!")
}
}

关于ios - 在 swift 2 中从 plist 读取时无法创建 NSDictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35411747/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com