Search code examples
core-datamany-to-manynsarraycontrollernspopupbutton

Many-to-Many entities and NSPopUpButton


all.

Entities:

[Library {title}] <-->> [Book {title}] <<-->> [Author {name}]

Controllers:

NSArrayController [Library] => {Entity: Library}
NSArrayController [Book] => {Entity: Book, ContentSet: Library, books}
NSArrayController [Author] => {Entity: Author, ContentSet: Book, authors}
NSArrayController [Authors] => {Entity: Author}

Form:

[ NSPopUpButton *]
[ NSTableView **]
[ add ] [ remove ]

* button get content from NSArrayController [Author w/o contentset option]

** table get content from another NSArrayController [Author with contentset option set as Library.books]

Question:

how i can add Author into Book.authors from Author entity? (Use previous authors for any book)


Solution

  • 1) set PopUpButton property

       {
         Content: NSArrayController [Authors], ArrangedObjects
         Content Values: NSArrayController [Authors], ArrangedObjects, name
         Selected Index: NSArrayController [Authors], selectionIndex
       }
    

    2) add

    @property (assign) IBOutlet *authorsController, *bookController; 
    

    and link it with NSArrayControllers

    3) add this code and link with button:

    - (IBAction)insertSelectedItem:(id)sender
    {
        MOAuthor *author = self.authorsController.content[self.authorsController.selectionIndex]; // get current (selected) author
    
        MOBook *book = self.bookController.content[self.bookController.selectionIndex]; // get current guide
    
        [book addAuthorsObject:author]; // add step into guide
    
        NSError *err = nil;
    
        [book.managedObjectContext save:&err]; // save all
    }
    

    MOBook, MOAuthor - ManagedObject class created from Entity