views:

354

answers:

2

I have recently been looking at Core Data for the iPhone and I have one query which I have not been able to find an answer to in the literature.

Lets imagine that I have a User model object with a to-many relationship with a Purchase object. A User may have thousands of purchases.

All of the information I have seen thus far seems to suggest that a fetch operation carried out across that relationship would return an NSSet with all of the Purchase objects associated with a particular User.

Clearly I would prefer if there was some way to limit the number of Purchase objects fetched by:

1) imposing some sort of criteria (e.g. only purchases over £1000 etc.); or

2) only fetching in batches if the above is not possible.

Is the above possible? I am just concerned that with the limited memory of the iPhone that I risk overloading it with thousands of unnecessarily fetched objects.

Thanks in advance for any replies.

+1  A: 
  1. Use a fetched property
  2. Use NSFetchedResultsController

The answer to these and the questions you will have next are answered in the Core Data Programming Guide for the iPhone.

Barry Wark
+1  A: 

My understanding is that when you fetch User objects, the relationship to its Purchase objects will be a fault that will only be loaded if accessed.
Instead, you could fetch Purchase objects with a predicate that specifies the User(s) and check(s) on any other criteria.

That said, I would definitely test realistic use cases (on devices) before spending too much time on performance issues. The efficiency of the iPhone and Core Data may surprise you.

gerry3
Not sure if I should be opening a new question based on your answer so I'll ask here first: 1) Once the Purchase fault is fired, does that mean every single Purchase object for that User gets loaded too? 2) If I use a predicate instead, do I not rely on the User -->> Purchase relationship at all, and instead use some other field to link a User to its Purchases and a completely different fetch request?
BoltClock
Not sure. Probably worth opening a new question if you haven't already or reviewing the Core Data Programming Guide (linked by Barry Wark's answer).
gerry3