【发布时间】:2018-02-09 08:18:51
【问题描述】:
错误的来源。
@objc func selectHeader(sender: UIButton) -> Void {
var testSection = NSDictionary()
var openValue = String()
testSection = self.arrHeader.object(at: sender.tag) as! NSDictionary
openValue = testSection.value(forKey: self.isOpenKey) as! String
// value change
if openValue == "Y" {
testSection.setValue("N", forKey: self.isOpenKey) <—— App crash self.isOpenKey == “openKey”
} else {
testSection.setValue("Y", forKey: self.isOpenKey) <—— App crash self.isOpenKey == “openKey”
}
let section: NSIndexSet = NSIndexSet(index: (sender.tag))
self.collectionView.reloadSections(section as IndexSet)
}
TestSection.setValue 崩溃并出现以下错误。
2018-02-09 16:43:38.141[10730:2091077] * 由于未捕获的异常“NSUnknownKeyException”而终止应用程序,原因:“[<_ttgcs26_swiftdeferrednsdictionaryssss_0x1665dea0> setValue:forUndefinedKey:]:这个类不是键值编码兼容键 openKey。 * 首先抛出调用栈: libc++abi.dylib:以 NSException 类型的未捕获异常终止
有什么问题?
【问题讨论】:
-
您的 isOpenKey 变量在哪里定义?永远不要使用 value(:forKey)...这是通往地狱的一种方式...
-
isOpenKey是一个什么样的var?看起来像一个布尔。您不能将 Bool 用作字典键。
-
类 ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource { @IBOutlet weak var collectionView: UICollectionView! let headerKey: String = "headerKey" let isOpenKey: String = "openKey" 我已经设置好了。
-
好的。那么 testSection 在崩溃点的值是多少呢?如果它是 nil 那就不好了。
-
如果取isOpenKey在crash前的值,会正常打印“N”。
标签: swift uicollectionview nsdictionary setvalue