【发布时间】:2015-03-13 11:29:14
【问题描述】:
我有一个 UITableViewController 通过 NSFetchedResultsController 从 Core Data 加载其条目。像这样:
let historyItem = fetchedResults.objectAtIndexPath(indexPath) as HistoryItem
historyItem 有一个 title 属性定义如下:
@NSManaged var title: String
但不知何故,在某些条目中,核心数据的 title 值为 nil,这会导致 EXC_BAD_ACCESS,因为 title 不是 String?。这个问题已经在Check if property is set in Core Data? 得到了解决,那里的高票回答暗示了这样的事情:
if let possibleTitle = historyItem.title as String? {
NSLog("possibleTitle was set OK")
} else {
NSLog("possibleTitle was nil")
}
但我刚刚尝试过,它仍然给了我 EXC_BAD_ACCESS:
同样的问题和解决方案也在 Swift - casting a nil core data string as an optional value 和我之前重复的问题Swift: handling an unexpected nil value, when variable is not optional 但这对我不起作用。我正在使用 Xcode 6.2 和 iOS8。
请问我是不是误会了什么?这种方法应该奏效吗?
【问题讨论】:
-
这很有趣。我可以确认stackoverflow.com/a/25664102/1187415 中提出的
as String?解决方案不再适用于 Xcode 6.2(在 iOS 8 模拟器中测试)。将属性类型更改为可选(stackoverflow.com/a/25664102/1187415 中的“旧答案”)仍然有效。 -
这也在开发者论坛中进行了讨论:devforums.apple.com/message/995243#995243、devforums.apple.com/message/1110385#1110385,建议提交错误报告。
-
item.valueForKey("title") as String?stackoverflow.com/a/27412036/1187415 中的提议也可以。 -
啊!谢谢你,@martin-r!我试过
item.valueForKey("title") as String?,这对我有用。但没有其他任何事情发生。如果你想提出这个作为答案,我很乐意打勾。谢谢! -
解决方案“作为字符串?”每次都不起作用。对于 CoreData 中的 NSDate 非可选 nil ,仅当我之前将其登录到 printf 时才有效。这根本没有意义。
标签: swift core-data null optional