简体   繁体   English

CoreData获取嵌套对象

[英]CoreData fetch nested objects

I have a json which contain objects where each object have child object, for example 我有一个包含对象的json,其中每个对象都有子对象,例如

[
    {
        "id": 1,
        "name": "obj1"
    },
    {
        "id": 2,
        "name": "obj2"
    },
    {
        "id": 3,
        "name": "obj3",
        "child": {
            "id": 2,
            "name": "obj2"
        }
    },
    {
        "id": 4,
        "name": "obj4",
        "child": {
            "id": 5,
            "name": "obj5"
        }
    }
]

So in core data i have entity MyObject which has relation to child (to itself, to one), and relation to parent (to many) 因此,在核心数据中,我有实体MyObject,它与子对象(与自身,与一个)相关,并且与父对象(与许多)相关

在此处输入图片说明

So when i try fetch object by predicate like 所以当我尝试通过谓词获取对象时

[NSPredicate predicateWithFormat:@"parent.@count = 0"]

I got only object with id in [1,3,4], but no with id = 2 (here error) and id = 5 (here all correct), because it's was sets parent when it's mapped when object with id = 3 save to data base. 我在[1,3,4]中只有id为id的对象,而id = 2(此处为错误)和id = 5(此处均为正确)的对象为no,因为当id = 3的对象保存时,它在映射时设置为父对象到数据库。

If no use predicate i got 5 object, include obj5. 如果没有使用谓词,我有5个对象,则包括obj5。

But i need fetch from coredata exactly count of object what i got from json. 但是我需要从coredata中获取从json获得的对象的确切计数。

I need fetch only object with id in [1,2,3,4]. 我只需要获取ID为[1,2,3,4]的对象。

How do i need write predicate, if it's possible? 如果可能,我如何需要写谓词?

The data you got from JSON is a subset of all your objects, but the logic according to which it is selected is not persisted in your object model. 从JSON获得的数据是所有对象的子集,但是选择该对象所依据的逻辑不会保留在您的对象模型中。

You persist the relationship between child and parent (hint: for readability, rename it as parents if it is to-many), but the selection in your JSON example is not based on any of those criteria. 你坚持下去的孩子和父母之间的关系(提示:为便于阅读,其重命名为parents如果是多),但在你的JSON例子的选择并非基于任何标准。

One easy way to get all the objects is to extract the top level ids delivered by the JSON feed and use that in the predicate: 获取所有对象的一种简单方法是提取JSON提要提供的顶级ID并将其用于谓词中:

NSArray *ids = [jsonArray valueForKey:@"id"];
[NSPredicate predicateWithFormat:@"idNumber in %@", ids];

(Note that I changed your attribute name from id to idNumber in order to avoid possible language quirks, as id is a reserved word.) (请注意,由于id是保留字,因此我将属性名称从id更改为idNumber以避免可能的语言怪癖。)

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

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