CoreData:Not null 属性应该是可选的吗?

Posted

技术标签:

【中文标题】CoreData:Not null 属性应该是可选的吗?【英文标题】:CoreData: Not null property should be optional? 【发布时间】:2015-03-17 07:28:17 【问题描述】:

我不确定 Swift 和 CoreData 的最佳实践。你认为 not null 属性基本上应该是可选的吗?

例如

import Foundation
import CoreData

class Item: NSManagedObject 
    @NSManaged var itemId: String // Not null property
    @NSManaged var itemPrice: String? // null is possible

我想知道我应该通知其他程序员哪个属性不为空。

我想知道你通常做什么。这个问题听起来是基于意见的,但我确信处理可选项对其他人有帮助。

仅供参考,我发现了类似的问题

CoreData - Setting a property of entity to be not null - Should the attribute be set as Optional or Mandatory

【问题讨论】:

Swift + CoreData: Cannot Automatically Set Optional Attribute On Generated NSManagedObject Subclass的可能重复 【参考方案1】:

来自https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreData/Articles/cdMOM.html#//apple_ref/doc/uid/TP40002328-SW6 .. 明确提到 - 您可以指定一个属性是可选的——也就是说,它不需要有值。但是,通常不鼓励您这样做——尤其是对于数值(通常,您可以使用具有默认值(在模型中)为 0 的强制属性获得更好的结果)

【讨论】:

非常感谢。好吧,一般情况下,我将为可能为 null 的属性设置可选值,如果需要,我将设置默认值。 @zono 如果答案合适,则使其接受答案,以便对其他人有用。

以上是关于CoreData:Not null 属性应该是可选的吗?的主要内容,如果未能解决你的问题,请参考以下文章

插件 jsonschema2pojo:属性按要求显示,但它们应该是可选的

CoreData - 原始访问器作为属性?

Coredata 轻量级迁移失败

如果没有可选关系属性的值,核心数据不会加载?!?迅速

为啥 UITableViewCell textLabel 属性是可选的?

MySQL字段的属性应该尽量设置为NOT NULL