[英]Swift: detecting an unexpected nil value in a non-optional at runtime: casting as optional fails
I have a UITableViewController
loading its entries from Core Data via a NSFetchedResultsController
. 我有一个
UITableViewController
通过NSFetchedResultsController
从Core Data加载其条目。 Like this: 像这样:
let historyItem = fetchedResults.objectAtIndexPath(indexPath) as HistoryItem
historyItem
has a title
property defined like this: historyItem
具有如下定义的title
属性:
@NSManaged var title: String
but somehow the core data has a nil value for title
in some entries which causes EXC_BAD_ACCESS because title
is not String?
但是以某种方式核心数据在某些条目中
title
值为零,这会导致EXC_BAD_ACCESS,因为title
不是String?
. 。 This problem has been addressed at Check if property is set in Core Data?
在“ 检查核心数据中是否设置了属性?”中已解决此问题。 and the high-voted answer there suggests something like this:
投票率很高的答案建议如下:
if let possibleTitle = historyItem.title as String? {
NSLog("possibleTitle was set OK")
} else {
NSLog("possibleTitle was nil")
}
but I just tried that and it still gave me EXC_BAD_ACCESS: 但是我只是尝试了一下,仍然给了我EXC_BAD_ACCESS:
That same problem and solution is also mentioned at Swift - casting a nil core data string as an optional value and my earlier duplicate question Swift: handling an unexpected nil value, when variable is not optional but it doesn't work for me. Swift也提到了相同的问题和解决方案-将nil核心数据字符串强制转换为可选值,而我先前的重复问题Swift:当变量不是可选的但对我不起作用时,处理意外的nil值 。 I'm using Xcode 6.2 and iOS8.
我正在使用Xcode 6.2和iOS8。
Am I misunderstanding something, please? 请问我误会了吗? Should this approach work?
这种方法行得通吗?
I think you should make your title an optional if core data can return nil value for title 我认为如果核心数据可以为标题返回nil值,则应该将标题设为可选
@NSManaged var title: String?
And test it without the cast 并在没有演员表的情况下对其进行测试
if let possibleTitle = historyItem.title{
NSLog("possibleTitle was set OK")
} else {
NSLog("possibleTitle was nil")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.