Swift - 将nil核心数据字符串转换为可选值 [英] Swift - casting a nil core data string as an optional value

查看:202
本文介绍了Swift - 将nil核心数据字符串转换为可选值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个存储在名为metadata的核心数据对象上的字段,其类型为 String (不可选,因为Apple文档说不要乱用CD中的选项)。有时,元数据字段为零。在检查此值是否为nil时,我执行以下检查:

I have a field stored on a core data object called "metadata" which is of type String (no optional, because Apple docs say not to mess with optionals in CD). Sometimes, the metadata field is nil. In checking whether this value is nil, I do the following check:

if object.metadata as String? != nil {
    ...
} 

然而,我的代码不断此行崩溃为 EXC_BAD_ACCESS 。我也尝试过:

However, my code continuously crashes on this line as an EXC_BAD_ACCESS. I have also tried:

if let metadata = object.metadata as String? {
    ...
}

这也不起作用。我成功地将对象转换为代码的其他部分中的选项,所以我不明白为什么这个特殊情况不起作用。如何检查核心数据属性是否为零字符串?

Which doesn't work either. I cast objects successfully to optionals in other parts of my code, so I don't understand why this particular case isn't working. How do you check whether a core data property is a nil string?

推荐答案

看起来你真正想要的是:

It looks like what you really want is this:

if object.metadata != nil {
    ...
}

或者这个:

if let metadata = object.metadata as? String {
    // You can now freely access metadata as a non-optional
    ...
}

- 编辑 -

我的错误,我没看过你的第一部分问题彻底彻底。看起来重复的答案有一个解决方案。本质上,生成的托管对象子类是一个错误,您应该将属性修改为可选或隐式展开。您可以使用第一种方法检查这两种方法以进行隐式展开,第二种方法检查选项。

My mistake, I didn't read the first part of your question thoroughly enough. It looks like the duplicate answer has a solution for this. Essentially, the generated managed object subclass is a bug and you should modify the properties to be either optional or implicitly unwrapped. You can check both of those using the first method for implicitly unwrapped and second for optionals.

有几个问题讨论了生成的子类不生成可选属性的问题。我不会太在意编辑子类;除了Apple让它更容易创建它们之外没有什么特别之处。

There are several questions which discuss the issue of the generated subclasses not producing optional properties. I wouldn't be too concerned about editing the subclasses; there's nothing special about them except that Apple is making it easier to create them.

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

Swift + CoreData:无法在生成的NSManagedObject子类上自动设置可选属性

- 编辑2 -

如果真的不希望触及您可以使用 valueForKey()访问该属性的子类,如果您想要更清洁的东西,可以将其添加为扩展名。

If you really don't want to touch the subclass you can access the property using valueForKey() and could add that as an extension if you wanted something a bit cleaner.

if let metadata = object.valueForKey("metadata") as String? {
    ...
}

在扩展程序中:

extension ObjectClass {
    var realMetadata: String? {
        set {
            self.setValue(newValue, forKey: "metadata")
        }
        get {
            return self.valueForKey("metadata") as String?
        }
    }
}

这篇关于Swift - 将nil核心数据字符串转换为可选值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆