我已经尝试将数组值设置为字典键的数组。这是我的密码
这是我的时隙数组初始化:
arrmTimeSlots = [
["time": "6am", "action": []],
["time": "7am", "action": []],
["time": "8am", "action": []],
["time": "9am", "action": []],
["time": "10am", "action": []],
["time": "11am", "action": []],
["time": "12pm", "action": []],
["time": "1pm", "action": []],
["time": "2pm", "action": []],
["time": "3pm", "action": []],
["time": "4pm", "action": []],
["time": "5pm", "action": []],
["time": "6pm", "action": []],
["time": "7pm", "action": []],
["time": "8pm", "action": []],
["time": "9pm", "action": []],
["time": "10pm", "action": []]
];我最初在tableview上显示了'time‘键的值。当用户从日历中选择日期时,我从相应的数据库获取数据到选定的日期。数据采用字典格式,如下所示:
{
"Description" = "this is discription";
"End_time" = 201601240645;
"Location" = "xyz";
"Rec_uid" = "r576thg8ed-698a-4a71-87e5-366bec44638a";
"Satrt_time" = 201601240645;
"Title" = "hrhrcffu";
"uid" = "c39b2987-5d19-4178-8591-c052b5205ad5";
}因此,我想在ArrmTimeSlots数组中为"action“键添加此字典。下面是我在数组中添加字典的代码:
for scheduleDay in arrmTimeSlots
{
let day = scheduleDay as! NSDictionary
let timeOnSlots = day["time"] as! String
let action = day["action"] as! NSArray
print("time \(timeOnSlots) action \(action)")
if(timeOnSlots == concatTimeslotTime) // here compare time if true set array to action key
{
day.setValue(array, forKey: "action")
}
}但是,我的应用程序崩溃了,并获得了‘d.setValue(数组,forKey:“action”)--这一行的错误:
终止应用程序,原因:'<_TtGCSs29_NativeDictionaryStorageOwnerSSCSo8NSObject_ 0x1566dbc0> setValue:forUndefinedKey::该类不符合键操作的键值编码。*第一次抛出调用堆栈:(0x240dc0dd7 0x3x0d7 0x32778c77 0x240dbde5 0x24d71c95 0x24d71c95 0x1ea1c4 0x1e7888 0x1e57f4 0x1e57f4 0x1e5974 0x107c2b 0xfc95d 0xddd369 0x2793f495 0x2793f197 0x8x4cb9 0x8b4c9)
请建议我解决这个问题的办法。提前谢谢!
发布于 2016-01-22 15:49:07
您将需要用修改过的对象覆盖数组项。您可以在每次迭代中同时使用enumerate()获取索引和对象。
其次,在声明day变量时,需要使用var而不是let,以便可以修改它。
下面是一个示例代码:
for (i, scheduleDay) in arrmTimeSlots.enumerate()
{
var day = scheduleDay
let timeOnSlots = day["time"]
let action = day["action"]
print("time \(timeOnSlots) action \(action)")
if(timeOnSlots == concatTimeslotTime) // here compare time if true set array to action key
{
day["action"] = array
arrmTimeSlots[i] = day
}
}发布于 2016-01-22 15:51:33
您的重复循环效率很低,因为即使第一项已经与时间匹配,也会对所有项进行评估。
乍一看,NSArray和NSDictionary似乎更方便,因为您不必处理该类型,但这是一个错误的结论。
这是一个本机Swift解决方案,取代了整个重复循环。如果使用indexOf函数获取数组的索引,则在必要时分配数组,并更新arrmTimeSlots数组中的项。
唯一的缺点是,由于Swift集合类型的值类型语义,您必须将子项分配回父项。
if let indexOfTimeOnSlots = arrmTimeSlots.indexOf( { $0["time"] as! String == concatTimeslotTime }) {
var item = arrmTimeSlots[indexOfTimeOnSlots]
item["action"] = array
arrmTimeSlots[indexOfTimeOnSlots] = item
}我建议对struct项使用自定义arrmTimeSlots,而不是使用字典。它可以避免更多的类型铸造。
发布于 2017-10-19 10:34:54
您的问题是,您已经将其声明为NSDictionary,所以让它成为NSMutableDictionary,它就能工作了。:)
https://stackoverflow.com/questions/34948532
复制相似问题