在 NSCoder 中展开可选值时意外发现 nil
Posted
技术标签:
【中文标题】在 NSCoder 中展开可选值时意外发现 nil【英文标题】:Unexpectedly found nil while unwrapping an Optional value in NSCoder 【发布时间】:2017-09-25 08:11:02 【问题描述】:isSelected(Bool)
出现零错误。请查看下面的屏幕截图以获取更多详细信息。
导入基础
class StatusEntity: `NSObject`, `NSCoding`
var Value: String
var Native_Description: String
var isSelected: Bool
override init()
Value = ""
Native_Description = ""
isSelected = false
@objc required init(coder aDecoder: NSCoder)
Value = aDecoder.decodeObject(forKey: "Value") as! String
Native_Description = aDecoder.decodeObject(forKey: "Native_Description") as! String
isSelected = aDecoder.decodeObject(forKey: "isSelected") as! Bool
@objc func encode(with aCoder: NSCoder)
aCoder.encode(Value, forKey: "Value")
aCoder.encode(Native_Description, forKey: "Native_Description")
aCoder.encode(isSelected, forKey: "isSelected")
这是CollectionView
代码
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) ->UICollectionViewCell
let cell: StatusCheckCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "statusCollectionCell", for: indexPath) as! StatusCheckCollectionViewCell
let entity: StatusEntity = arrayList[indexPath.item]
cell.txtName.text = entity.Native_Description
// Making CollectionView Cell Right Align
var scalingTransform : CGAffineTransform!
scalingTransform = CGAffineTransform(scaleX: -1, y: 1);
cell.transform = scalingTransform
cell.btnItem.tag = indexPath.row
cell.btnItem.addTarget(self, action: #selector(StatusTableViewCell.onItemClicker(_:)), for: UIControlEvents.touchUpInside)
if(entity.isSelected)
cell.imgCheckBox.image = UIImage(named: "CheckBoxSelected")
else
cell.imgCheckBox.image = UIImage(named: "CheckBox")
return cell
func onItemClicker(_ sender: UIButton)
let entity: StatusEntity = arrayList[sender.tag]
entity.isSelected = !entity.isSelected
let indexPath: IndexPath = IndexPath(row: sender.tag, section: 0)
collectionView.reloadItems(at: [indexPath])
// Saving values to DB
var submitEntity: SubmitDocumentEntity = SubmitDocumentEntity()
let insertEntity = dataStorage.getSubmitDocumentEntity()
if(!insertEntity.isKind(of: NSNull.self))
submitEntity = dataStorage.getSubmitDocumentEntity() as! SubmitDocumentEntity
if(entity.isSelected)
if(!submitEntity.TransactionTypes.contains(entity.Value))
submitEntity.TransactionTypes.append(entity.Value)
else
if(submitEntity.TransactionTypes.contains(entity.Value))
let index = submitEntity.TransactionTypes.index(of: entity.Value)
submitEntity.TransactionTypes.remove(at: index!)
dataStorage.putSubmitDocumentEntity(submitEntity)
【问题讨论】:
@vadian 感谢更新和回答。 【参考方案1】:您将解码一个对象。就NSCoding
而言,Bool
不是 对象。
原始类型有专门的方法。
isSelected = aDecoder.decodeBool(forKey: "isSelected")
请遵守变量名以小写字母开头并且是camelCased而不是snake_cased
的命名约定【讨论】:
以上是关于在 NSCoder 中展开可选值时意外发现 nil的主要内容,如果未能解决你的问题,请参考以下文章
致命错误:在快速 Json 解析中展开可选值时意外发现 nil