检查核心数据中是否设置了属性?

时间:2014-09-04 08:50:37

标签: ios swift core-data

如何检查是否在Core Data Object中设置了属性?

我将所有核心数据对象加载到目录中:

var formQuestions = [Questions]()

我的核心数据NSManagementObject是:

@NSManaged var noticeText: String

formQuestions [indexPath.row] .noticeText

//加载:

var fetchRequest = NSFetchRequest(entityName: "Questions")
fetchRequest.predicate = NSPredicate(format: "forms = %@", currentForm!)
formQuestions = context.executeFetchRequest(fetchRequest, error: nil) as [Questions]

我的属性“noticeText”可能是空的,所以当我创建我的核心数据对象时,可能无法设置某些值。 (该属性在Core Data中设置为可选)

当我现在尝试证明是否有值时,它总会给我带来“EXC_BAD_ACCESS ....”

if(formQuestions[indexPath.row].noticeText.isEmpty == false)

我可以在创建核心数据对象时设置一个空字符串,但这不是一个好的解决方案。

那么如何检查(optinal)和未设置的值是否存在?

提前致谢。

2 个答案:

答案 0 :(得分:29)

Xcode 7更新:此问题已通过Xcode 7 beta 2解决。 可选的Core Data属性现在定义为可选属性 在Xcode生成的托管对象子类中。它不再是 编辑生成的类定义所必需的。


(上一个回答:)

创建NSManagedObject子类时,Xcode没有为那些标记为"可选"的属性定义可选属性。在Core Data模型检查器中。 这看起来像是一个错误。

作为解决方法,您可以将属性转换为 一个可选的(在你的情况下为as String?),然后用可选的绑定

进行测试
if let notice = someManagedObject.noticeText as String? {
    println(notice)
} else {
    // property not set
}

在你的情况下

if let notice = formQuestions[indexPath.row].noticeText as String? {
    println(notice)
} else {
    // property not set
}

更新:从Xcode 6.2开始,此解决方案不再有效 和EXC_BAD_ACCESS运行时异常崩溃 (比较Swift: detecting an unexpected nil value in a non-optional at runtime: casting as optional fails

旧答案"以下解决方案仍有效。


(旧答案:)

正如@ Daij-Djan已经在评论中说明的那样,你必须定义一个属性 可选的Core Data属性为可选隐式解包可选

@NSManaged var noticeText: String? // optional
@NSManaged var noticeText: String! // implicitly unwrapped optional

不幸的是,Xcode在创建时没有正确定义可选属性 NSManagedObject子类,这意味着您必须重新应用更改 如果在模型更改后再次创建子类。

此外,这似乎仍然没有记录,但两种变体都适用于我的测试用例。

您可以使用== nil

测试该属性
if formQuestions[indexPath.row].noticeText == nil {
    // property not set
}

或使用可选作业:

if let notice = formQuestions[indexPath.row].noticeText {
    println(notice)
} else {
    // property not set
}

答案 1 :(得分:5)

您的应用程序崩溃是因为您尝试访问 nil not optional variable。这在swift中是不允许的。要解决您的问题,只需在NSManagedObject子类中添加?即可使该属性成为可选项:

@objc class MyModel: NSManagedObject {
    @NSManaged var noticeText: String? // <-- add ? here
}

然后测试你可以这样做的属性:

if let aNoticeText = formQuestions[indexPath.row].noticeText? {
    // do something with noticeText
}