简体   繁体   English

核心数据中的关系作为NSSet

[英]Relationship in Core Data as NSSet

I have an entity of Category and an entity of Subcategory. 我有一个类别的实体和一个子类别的实体。 it is one to many as one category can have many subcategories. 它是一对多的,因为一个类别可以有许多子类别。 I'm still trying to wrap my head around all this so bear with me... 我仍在努力将所有事情缠住,所以请忍受...

extension Category {
    @NSManaged var name: String?
    @NSManaged var subCategory: SubCategory?
}


extension SubCategory {
    @NSManaged var name: String?
}

and then somewhere else in the code such as some view controller I make this call 然后在代码中的其他地方(例如某些视图控制器)进行调用

let category = NSEntityDescription.insertNewObjectForEntityForName("Category", inManagedObjectContext: self.context) as! Category
let sub = SubCategory()
sub.name = "sub1"

category.subCategory = sub

//save it

And then when I look at the actual core data Sqlite db, I can see that the ZSUBCATEGORY column of the Category entity is populated with the primary key value of the sub category entity. 然后,当我查看实际的核心数据Sqlite db时,可以看到Category实体的ZSUBCATEGORY列填充有sub category实体的主键值。 I have defined the relationship in the data model. 我已经在数据模型中定义了关系。

My question is, I've noticed that some relationships are stored with a NSSet. 我的问题是,我注意到某些关系是通过NSSet存储的。 Is there any benefit in doing this? 这样做有什么好处吗? Is what I'm doing wrong and egregious? 我在做错事吗? To me this just seems simpler as I can then do... 对我来说,这似乎比较简单,然后我可以做...

category.subcategory.name 

to get the subcategory name 获取子类别名称

If it was one to one relationship, indeed you could do this: 如果这是一对一的关系,那么确实可以做到这一点:

category.subcategory.name 

And that is what you are doing in this example, you have defined one to one relationship. 这就是您在此示例中所做的,已经定义了一对一关系。 If you want one to many than you would define it: 如果要比定义多一:

extension Category {
    @NSManaged var name: String?
    @NSManaged var subCategory: NSSet?
}

This way category is linked with number of sub categories, so if you would do 这种方式将类别与子类别的数量链接在一起,所以如果您愿意

category.subcategory.name

how do you know which sub category you are accessing? 您怎么知道您正在访问哪个子类别? You would have to iterate through set, to find one subcategory you want to find. 您将不得不遍历set,以找到要查找的一个子类别。

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

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