ios - Efficient way to get relationship count in database -
i want know best way count of related entities in to-many relationship. let's have data model looks (simplified), , want know number of passengers each bus:
currently can think of 2 options:
add attribute bus entity called passengercount updated every time passenger added/removed.
every time count of passengers needs displayed, it's done fetching passengers , displaying count.
both of options seem quite inefficient, though i'm not aware how heavy update/fetch values core data. example, imagine doing number 2 every table view cell.
my question is: best way this? method in nsmanagedobject class perhaps (i couldn't find any) or other way more efficient?
three remarks @ beginning:
a. should care efficiency when have runtime problem. "premature optimization root of evil." (donald knuth)
b. said passenger entities has fetched? think of …
[bus.passengers count]
… causing passengers fetched. core data supports faulting, maybe entities maybe fetched fault. (having id, not full object.)
c. can see core data does, when turn verbose mode on. pass launch argument
-com.apple.coredata.sqldebug 1
to question itself:
if have problem, can ask count explicitly -countforfetchrequest:error:
.
nsfetchrequest *fetch = [nsfetchrequest fetchrequestwithentityname:@"passenger"]; fetch.predicate = [nspredicate predicatewithformat:@"bus == %@", bus]; … nsuinteger count = [context countforfetchrequest:fetch error:null]; // please pass nserror instance in real world
typed in safari.
Comments
Post a Comment