Question

I have 2 NSManagedObjects, table & field and table has a one-to-many relationship with field i.e.

table <------>> field

Up to now I have been able to loop through field like so:

for (NSManagedObject *field in [table valueForKey:@"fields"]) {
}

however I now need to do this in a specific order using an integer index attribute from the field entity.

I'm new to Core Data so I had assumed that [table valueForKey:@"fields"] would return an array of NSManagedObject's but that doesn't seem to be the case.

How can I do this?

Was it helpful?

Solution

A to-many relationship is represented as an NSSet when using valueForKey:.

To turn that into a sorted NSArray, you can use the sortedArrayUsingDescriptors: method:

NSSet *allFields = [table valueForKey:@"fields"];
NSSortDescriptor *indexSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"index" ascending:YES];
NSArray *sortedFields = [allFields sortedArrayUsingDescriptors:@[indexSortDescriptor]];

OTHER TIPS

[table valueForKey:@"fields"] should return NSOrderSet not NSArray, so that you can fetch the object using [orderSet objectAtIndex:index].

You must manage the fields Relationships in table like this below :

enter image description here

There is a bug when Xcode generate accessors on To-Many-Relationships, check this Exception thrown in NSOrderedSet generated accessors

I'm sure there are better solutions but this is the best I could come up with!

fields = [NSMutableDictionary new];
for (NSManagedObject *fld in [table valueForKey:@"fields"])
{
    [fields setValue:fld forKey:[fld valueForKey:@"index"]];
}

for (int i = 0; i < [fields count]; i++)
{
    field = [fields objectForKey:[NSNumber numberWithInt:i]];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top