Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate an NSSet (Objective-C) - To-Many relationship representation in Core Data - efficiently?

To-Many relationships in Core Data are represented by NSSet (as automatically generated by using the Editor... Create NSManagedObject Subclass.. menu.

Which is the most efficient way to iterate an NSSet* ?

NSSet* groups = [contact groups];
for(Group* group in groups) {
    NSString* groupName = [group name];
}

or

NSSet* groups2 = [contact groups];
NSArray* groupsArray = [groups2 allObjects];
for(Group* group in groupsArray) {
    NSString* groupName = [group name];
}

or another way?

like image 215
ikevin8me Avatar asked Sep 28 '12 07:09

ikevin8me


1 Answers

The first is probably more efficient. If the latter were more efficient then Apple would simply use that route to implement the former.

That being said, if you're asking because performance seems to be an issue it's probably more that you're spending a lot of time on the Core Data stuff of faulting objects. A smart move would be to do a fetch on self in %@ with groups; set the fetch request's returnsObjectsAsFaults to NO and ensure any appropriate relationshipKeyPathsForPrefetching are specified. The net effect of that will be that all the data you're about to iterate through is fetched in a single trip to the backing store rather than each individual piece of it being fetched on demand in a large number of separate trips.

like image 107
Tommy Avatar answered Oct 20 '22 21:10

Tommy