Jonathan Penn
Jonathan Penn

Reputation: 33

Implementing Tagging using Core Data on the iPhone

I have an application that uses CoreData and I'm trying to figure out the best way to implement tagging and filtering by tag. For my purposes, if I was doing this in raw SQLite I would only need three tables, tags, item_tags and of course my items table. Then filtering would be as simple as joining between the three tables where only items are related to the given tags. Quite straightforward.

But, is there a way to do this in CoreData and utilizing NSFetchedResultsController? It doesn't seem that NSPredicate give you the ability to filter through joins. NSPredicate's aren't full SQL anyway so I'm probably barking up the wrong tree there. I'm trying to avoid reimplementing my app using SQLite without CoreData since I'm enjoying the performance CoreData gives me in other areas. Yes, I did consider (and built a test implementation) diving into the raw SQLite that CoreData generates, but that's not future proof and I want to avoid that, too.

Has anyone else tried to tackle tagging/filtering with CoreData in a UITableView with NSFetchedResultsController

Upvotes: 3

Views: 1066

Answers (1)

Alex
Alex

Reputation: 26859

First of all, you actually don't need an Item_Tags entity. Core Data is able to model many-to-many relationships without the need for an intermediate entity. You can have a to-many tags relationship that has a reciprocal to-many items relationship and Core Data will do all the magic to make that happen behind the scenes.

So, to set up a fetch request to do what you describe, you'd do something like this. Suppose you have a tag that represents the tag you want to filter on. Write a predicate like this:

[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"%@ IN tags", tag]];

This will give you a predicate that returns only Items that have tag in their set of tags relationships. Pretty easy, huh?

Remember: Core Data is not a database. It's an object graph management system. The fact that it uses SQL behind the scenes really shouldn't influence the way you use it.

Upvotes: 9

Related Questions