简体   繁体   English

Swift - 将nil核心数据字符串作为可选值进行转换

[英]Swift - casting a nil core data string as an optional value

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). 我有一个存储在核心数据对象上的字段,称为“元数据”,其类型为String (不是可选的,因为Apple文档说不要乱用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 {
    ...
} 

However, my code continuously crashes on this line as an EXC_BAD_ACCESS . 但是,我的代码在此行上连续崩溃为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 {
    ...
}

or this: 或这个:

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

--EDIT-- - 编辑 -

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. 您可以使用第一种方法检查这两种方法,用于隐式展开,第二种方法用于选项。

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. 除了Apple让它们更容易创建它们之外没有什么特别之处。

Check if property is set in Core Data? 检查核心数据中是否设置了属性?

Swift + CoreData: Cannot Automatically Set Optional Attribute On Generated NSManagedObject Subclass Swift + CoreData:无法在生成的NSManagedObject子类上自动设置可选属性

--Edit2-- --Edit2--

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. 如果你真的不想触摸子类,你可以使用valueForKey()访问该属性,如果你想要更清洁一点,可以添加它作为扩展。

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

In an extension: 在扩展中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM