Monday, August 14, 2017

Swift 3 - CoreData - To Many - Inverse Relationship (Tutorial-5)

In the last tutorial we have seen 'To One - Inverse relationship' with a person spouse as an example.

In this tutorial, Let’ see To Many - Inverse relationship.

Please checkout code for this example here

In this example, each person can have a manager (To One) and n number of reportees (To Many) If the person is a manager.





Here, 

Relationship ‘reportees’ 


If Person A is added as a reportee to Person B, as we have given Inverse relationship as manager,
Person B will become the manager for that reportee automatically.

Person A.manager = Person B (Inverse Relationship as manager)

As a person can have multiple reportees If he/she is a manager, reportees is having To Many type relationship with the person.

Relationship ‘manager’ 


If Person A is added as a manager to Person B, as we have given Inverse relationship as reportees,
Person B will become the reportee for that manager automatically.

Person B is now one of the reportees to Person B

As a person can have only one manager, manager is having To One type relationship with the person.


When there is a To Many relationship, Coredata gives it as a NSSet, which is unordered list with no duplicates.

Download the example and see the Person core data class.


  
   @NSManaged public var manager: Person?
    @NSManaged public var reportees: NSSet?



The beauty of core data is, It gives all accessor methods for adding and removing reportees when we create a Person NSManagedObject subclass.



  
extension Person {
    
    @objc(addReporteesObject:)
    @NSManaged public func addToReportees(_ value: Person)
    
    @objc(removeReporteesObject:)
    @NSManaged public func removeFromReportees(_ value: Person)
    
    @objc(addReportees:)
    @NSManaged public func addToReportees(_ values: NSSet)
    
    @objc(removeReportees:)
    @NSManaged public func removeFromReportees(_ values: NSSet)
    
 }



In the example, If the person is a manger, They can select reportees, Where I am using generated accessor method “addToReportees()”

Add Reportee


Reportee Selection


Added Reportee


Manager updated (Inverse Relationship)


Hope this post is useful. Feel free to comment incase of any queries.


No comments:

Post a Comment