0

Xcode 7, Swift 2, macOS application

Hello

I have a single Core Data entity named 'Task' which has a few properties including:

  • name (String)
  • type (String)
  • children (NSSet)
  • parent (Task)

This entity has 2 relationships defined:

  • 'children' (To Many)
  • 'parent' (To One)

I am displaying the Tasks in an NSOutlineView and they display hierarchically fine. I want Task.type to be set to 'Task' if the Task has no children (a leaf) or to be set to 'Group' if the Task does have children. I thought that I could call a simple update method (updateType) in a 'setter' as follows:

internal static let childrenKey = "children"
@NSManaged private var primitiveChildren: NSSet
internal var children: NSSet {
    set{
        //print("Task.children set called.")
        if (newValue != children){
            willChangeValueForKey(Task.childrenKey)
            primitiveChildren = newValue
            didChangeValueForKey(Task.childrenKey)

            updateType()
        }
    }
    get{
        //print("Task.children get called.")
        willAccessValueForKey(Task.childrenKey)
        let value = primitiveChildren
        didAccessValueForKey(Task.childrenKey)
        return value

    }
}

however this didn't get called when I insert a child into a Task.

In case it is significant, if a Task is selected in the NSOutlineView when my Add button is clicked the following function is called in the NSViewController:

    internal func addTask(){

    // Get the selected Task, if a Task is selected.
    let selectedRow = self.outlineView.itemAtRow(self.outlineView.selectedRow)

    // Establish if a Task is selected.
    if ((selectedRow) != nil) {

        // A Task is selected so we insert the new Task as a child of the selected Task.
        print("Task is selected")

        treeController.addChild(Task)

    } else {

        // No Task is selected so add a new Task at the root level.
        print("No task is selected")

        treeController.insertChild(Task)
    }
}

Thanks

Eiko
  • 25,601
  • 15
  • 56
  • 71
TDC
  • 1,869
  • 3
  • 25
  • 40
  • Core Data uses to-many relationship accessors `addChildrenObject`, `removeChildrenObject`, `addChildren` and `removeChildren`. – Willeke Jul 02 '16 at 13:31
  • Are you suggesting I replace `treeController.addChild` or `treeController.insertChild` with addChildren or addChildrenObject? I simply want to detect that a child has been added or removed so that I can set the `Task.type` property to either Group or Task. I'm looking into setting an Observer. – TDC Jul 05 '16 at 08:15
  • No, I suggest you override the Core Data to-many relationship accessors but I don't do Swift and can't give an answer. You can find a code snippet in Xcode. This answer mentions the accessors: http://stackoverflow.com/a/33573741/4244136. – Willeke Jul 05 '16 at 10:05

0 Answers0