I'm trying to access a relationship (one to many) programatically. My Data model contains an NSManagedEntity called language (with a two string attributes) with a relationship to an entity called WordCategory (one-to-many). I use an NSFetchRequest to get all the Language entities. that works fine. I get the valueForKey for the relationship and that works fine. I can work with its objects. However, when I try to send the message count to the NSSet that stores the WordCategory objects I get a
In other words, this line works:
NSLog(@"word category count %@",[[wordCategory anyObject] valueForKey:@"name"]);
This one doesn't:
NSLog(@"word category count %@",[wordCategory count]
I get a the message: EXC_BAD_ACCESS in the debugger.
Here's the rest of the code:
NSManagedObjectContext *moc = [myAppDelegate managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Language" inManagedObjectContext:moc]];
NSError *error = nil;
NSArray *results = [moc executeFetchRequest:request error: &error];
if (error) {
[NSApp presentError:error];
return;
}
NSManagedObject *obj = [results objectAtIndex:0];
NSSet *wordCategory = [obj valueForKey:@"category"];
NSLog(@"word category count %@",[wordCategory count]);
I'll appreciate any light than anybody can shed in this mystery. Thanks for your help!
The return type of the method count on NSSet is NSUInteger. So if you try to use %@ to refer to this type, you will get the message: EXC_BAD_ACCESS in debugger. You are accessing a type of value that is not expected.
Try using %d instead.
NSLog(@"word category count %d",[wordCategory count]);
Edited after bobDevil's comment (Accurate answer - more in comments):
NSLog(@"word category count %lu",[wordCategory count]);
All the best.