0

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?

rmaddy
  • 298,130
  • 40
  • 468
  • 517
doovers
  • 8,085
  • 10
  • 37
  • 67

3 Answers3

2

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]];
omz
  • 52,281
  • 5
  • 125
  • 139
1

[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

Community
  • 1
  • 1
KudoCC
  • 6,722
  • 1
  • 21
  • 48
  • Just set relationship type to ordered and am now getting the following exception "Cannot create NSSet from object Relationship 'fields' on managed object" Any idea why I might get this? – doovers Apr 17 '14 at 03:20
  • @doovers After changing the model, you should regenerate the subclass of NSManagedObject and delete the app on your device or simulator. – KudoCC Apr 17 '14 at 03:23
  • No joy unfortunately but according to [this](http://stackoverflow.com/questions/15078679/binding-an-ordered-relationship-with-an-nsarraycontroller#answer-15605624) it seems this won't work or am I wrong? – doovers Apr 17 '14 at 03:37
0

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]];
}
doovers
  • 8,085
  • 10
  • 37
  • 67