zztop
zztop

Reputation: 791

IOS/Core Data: How to fetch attribute from other entity through relationship

I have a master detail controller with core data that fetches objects from one entity, i.e. Authors, and then lets you look at one of those objects in detail,i.e. one author.

The author object has a one to many relationship with a second entity, Books. For each author, I would like to display a clickable list of their books.

My first question is after displaying the author page, how would I fetch a list of the books.

Eventually, I would like to display the list in a label or button as clickable text perhaps using NSAttributed Text but for now would be happy to just retrieve the list of books.

The authors have a relationship to books, entitled, book, that is one to many and the books have a reciprocal relationship to authors, entitled author, that is one to one.

I import books.h (data file) into the authorsVC.h and authorsDetail.h controllers.

The authors.h file has a property as follows:

@property (nonatomic, strong) Books *authorBook;

The following code does not throw an exception but logs out null.

 NSLog(@"books %@", _authorBook.bookname); //logs as null even when there are books for the author.

This code throws the exception shown:

NSLog(@"books %@", _author.book.bookname);

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_NSFaultingMutableSet bookname]: unrecognized selector sent to instance

Upvotes: 0

Views: 108

Answers (2)

zztop
zztop

Reputation: 791

The following code did the trick. Similar to Tom's whom I am not allowed to upvote given my rating but with a few adjustments as it would not accept the dot notation. The valueForKey is for an array.

NSSet *books = _book.author;
   NSArray *booksarr = [[files valueForKey:@"author"] allObjects];
   NSString *bookstr = [booksarr componentsJoinedByString:@","];

Once in a string, you can display it as needed.

Upvotes: 0

Tom Harrington
Tom Harrington

Reputation: 70976

To-many relationships in Core Data are realized as NSSet instances. In your case since Author -> Book is a to-many relationship, _author.book is an NSSet of Book instances-- which is the collection of books. Book may have an attribute called bookName but NSSet does not.

If you just want the book names, you'd use

_author.book.valueForKey[@"bookName"]

That will ask each Book in the set for its bookName and return a new set of just the book names.

Upvotes: 0

Related Questions