如果在子节点上找到子对象,如何递归地继续将子对象添加到父对象

时间:2017-07-10 13:22:38

标签: ios swift core-data

我有一个场景,我在json中得到子对象的列表,其键是

{
    "text": "Hellojson",
    "child": [{
        "somefirstchildkey": "somefirstchildValue",
        "child": [{
                "someSecondchildkey": "someSecondchildValue",
                "child": [{
                    "someSecondchildkey": "someSecondchildValue",
                    "child": [{

                    }]
                }]
            }

        ]
    }]
}

所以这就像嵌套的动态子。所以现在,我能够取得父母和孩子但是在这种情况下连续的孩子被添加到孩子所以在这种情况下,前一个孩子将成为下一个孩子的父母。 我实施的代码:

for currentCategory in categories{

                    var parentCategory : rootParent?
                    //  If the object exists use it
                    if let thisCategory = self.coreData.fetchWithPredicate(CoreDataEntities.MyCategories.rawValue, predicate: NSPredicate(format: "id = %@ ,thisCategoryID)) as? [MyCategories],
                        firstObject = thisCategory.first {
                        parentCategory = firstObject
                       )
                    }
                        ///  Insert a parent category as they're all top level from the API call
                    else {
                        parentCategory = self.coreData.insertNewObject(CoreDataEntities. MyCategories.rawValue,
                            keyValues: ["id" : currentCategory.id!]) as? MyCategories
                        Log.verbose?.message("Category inserted : \(parentCategory)")
                    }


                    /// Guard against if there are child categories
                    guard let children = currentCategory.children where children.count > 0 else {
                        //  Save the context
                        self.coreData.saveStore()
                        continue
                    }

                    for thisChildCategory in children {

                        //   If the child doesn't exist, then create a new one
                        //  Guard ID
                        guard let thisChildID = thisChildCategory.id else {
                            Log.verbose?.message("Category Child insertion error : No Child ID")
                            continue
                        }

                        //  Guard exisitance
                        if let currentChild = self.coreData.fetchWithPredicate(CoreDataEntities. MyCategories.rawValue, predicate: NSPredicate(format: "id == %@", thisChildID)) as? [MyCategories] where currentChild.count > 0 {
                            Log.verbose?.message("Category Child insertion not needed, already exists \(thisChildID), child \(currentChild)")
                            continue
                        }

                        //  Create new object
                        if let currentChildCategory  = self.coreData.insertNewObject(CoreDataEntities. MyCategories.rawValue,keyValues: ["id" : thisChildCategory.id!]) as? MyCategories {

                            //  Set as parent category
                            currentChildCategory.parentCategory = parentCategory


                            //  Save the context
                            self.coreData.saveStore()

                            Log.verbose?.message("Child Category Inserted \(currentChildCategory.id) with colours \(currentChildCategory.colours?.allObjects) and sizes \(currentChildCategory.sizes?.allObjects)")

                        }
                    }

                }

因此,使用此代码,我只能访问第一级父级,并且无法访问其相应的子级,内部子级和父级。

1 个答案:

答案 0 :(得分:0)

我可能做了一些拼写错误,也可能有类型错误但总的来说这应该有效。下面的函数将为孩子提供根。

func getRootCategoryForChildCategory(_ child:MyCategories) -> rootParent
{
    var recursiveCategory:rootParent = currentChildCategory.parentCategory

    while(true)
    {
        if (recursiveCategory.parentCategory != nil)
        {
            recursiveCategory = recursiveCategory.parentCategory
        }
        else
        {
            return recursiveCategory
        }

    }
}

然后做:

//  Set as parent category
currentChildCategory.parentCategory = parentCategory

self.getRootCatergoryForChildCategory(currentChildCategory).children.append(currentChildCategory)