Resolved Struggling with Core Data: Part 2

Discussion in 'iPhone/iPad Programming' started by RonC, May 23, 2011.

  1. RonC, May 23, 2011
    Last edited: May 27, 2011

    macrumors regular

    #1
    Next in what promises to be an unending series of questions about Core Data. This one has to do with following relationships and queries.

    Here's a simple data model: Screen shot 2011-05-23 at 7.51.24 PM.png

    There are two managed objects, Owner and Thing. Owner owns many things, but a thing is only owned by one owner. I want to test to see if a given thing exists, and if it does exist, if it's owned by a given owner (theOwner). If it doesn't exist, I'm going to create it and link it to theOwner (newThing.owner = theOwner).

    I know how to test if a given thing exists (with the assumption that the thing's name property is unique), but I don't know how to craft a fetch request such that it only looks for the ones that have owner = theOwner. Any pointers to how to create that fetch request?

    Is it as simple as looking in the theThing.things set to see if the Thing I'm looking for is there? If I only fetch theOwner, does it populate the set appropriately? Is this where the magic of "faulting" comes into play?

    Thanks!

    Ron
     
  2. macrumors 603

    Cromulent

    #2
    You want to look into the NSPredicate class for such things. This is really the class you should use for any queries you want to execute on your Core Data models as it allows you quite a bit of flexibility (think of it as Core Data's version of SQL).

    Look here for some info:

    http://developer.apple.com/library/.../Conceptual/CoreData/Articles/cdFetching.html
     
  3. macrumors regular

    #3
    Thanks. I did just that and have it working quite nicely now. I think I'm getting the hang of Core Data, Predicates, and NSFetchedResultsController.

    The predicate I am using, made appropriate for this example, is
    Code:
    (name = "TheThing") AND (owner.name = "TheOwner")
    (the quoted values are filled in via predicateWithFormat: %@ fields).

    Ron
     

Share This Page