user6631314
user6631314

Reputation: 1958

IOS/Objective-C: Detect if nsmanaged object linked to another nsmanagedobject in core data

I allow comments on different types of items in my app such as books and songs. To link the comment to the item, I create a relationship in core data.

Then to put the name of the item, ie a book, next to the comment I use the relationship. For a book title, I can use comment.book.title to get the title.

However, for a book the title will be comment.book.title but for a song, the title will be comment.song.title. For some comments, I created a relationship to a certain book and in others to a certain song. It is true that there is a formal relationship between the entities and attributes in Core Data. But I'm getting confused about those underlying relationships and the specific ones I create to make the association.

My immediate need is to detect if a relationship has been established.

Comments has one relationship book to books and another song to songs.

Should I use something like if

if (comment.book.title.length>=1) {
myLabel.text = comment.book.title;
}
else if (comment.song.title.length>=1) {
myLabel.text= comment.song.title;
}

Or what is the best way to do this?

Edit/Clarification:

The above code seems to work. Not sure if it is robust, however.

Thanks in advance for any suggestions.

Upvotes: 1

Views: 33

Answers (1)

pfandrade
pfandrade

Reputation: 2419

Your approach should work just fine. If you want something more generic, Core Data actually supports inheritance and abstract classes.

So you could make your Book and Song object inherit from a Content abstract super class. That class would hold common attributes between all subclasses, such as title, and a relationship to the Comment entity.

Here's a diagram of what I just said.

enter image description here

Then, to check get the title of the whatever the comment is related to, you just do: comment.content.title.

Upvotes: 2

Related Questions