我在CellForRowat Indexpath中使用For循环来改变颜色,但它向我显示错误如何解决它。并且我输入了正确的键值
错误(由于未捕获的异常而终止应用程序 'NSInvalidArgumentException',原因:' - [_ SwiftValue objectForKey:]: 无法识别的选择器发送到实例0x6040000f6680'
for all in arrayForType!
{
let type = (all as AnyObject).object(forKey: "type") as! String
print(type)
if type == "Send"
{
cell.lblForSend.backgroundColor = UIColor.red
}
else
{
cell.lblForSend.backgroundColor = UIColor.green
}
}
答案 0 :(得分:1)
您的问题是AnyObject
没有.object(forKey: #"")
方法,objectForKey方法是NSDictionary
的方法,这是您的崩溃原因
https://developer.apple.com/documentation/foundation/nsdictionary/1414347-objectforkey
答案 1 :(得分:0)
错误似乎在这一行:
let type = (all as AnyObject).object(forKey: "type") as! String
您将all
视为AnyObject
(顺便说一下,这是多余的),但您调用它的方法 - object(forKey: String)
- 是{{NSDictionary
的方法。 1}}类
相反,请尝试
guard let array = arrayForType else { return }
for all in array
{
guard let dict = all as? NSDictionary else { continue }
guard let type = dict.object(forKey: "type") as? String else { continue }
print(type)
if type == "Send"
{
cell.lblForSend.backgroundColor = UIColor.red
}
else
{
cell.lblForSend.backgroundColor = UIColor.green
}
}
另外,请避免使用强制解包选项(!
运算符),尽管这不是导致崩溃的原因
答案 2 :(得分:0)
我已经解决了问题,这是正确的方法。
let type = (arrayForType[indexPath.row] as AnyObject).object(forKey: "type") as! String
print(type)
if type == "Send"
{
cell.lblForSend.backgroundColor = UIColor.red
}
else
{
cell.lblForSend.backgroundColor = UIColor.green
}
答案 3 :(得分:-1)
您应该始终尽量避免隐式解包,尤其是在处理从服务器获取的数据时。尝试使用Optional Binding来实现更高的安全性。就像那样
guard let arrayForType = arrayForType as? [NSDictionary] else { return }
for all in arrayForType {
if let type = all.object(forKey: "type") as? String, type == "Send" {
cell.lblForSend.backgroundColor = .red
} else {
cell.lblForSend.backgroundColor = .green
}
}