Question

I am actually new to iPhone programming and have successfully create an app but I can't figure out how to retrieve the values stored in NSSet. I have 2 entities in core data related to each other. Users one-to-many to Scores. Users entity has firsNname and lastName attributes and Scores entity has onTime, wasAbsent, and dateIn attributes. I fetch using predicate based on firstName and lastName and then execute the fetch. The fetch is successful and I am able to get both entities in one fetch call. However I cannot get values for the values from Scores entity. Whatever I do, it always returns NSSet object. What I want to do is to retrieve the boolean value which was stored in onTime and wasAbsent attributes and feed them to UISwitch.

AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
self.managedObject = delegate.managedObjectContext;

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Student"];
    fetchRequest.predicate = [NSPredicate predicateWithFormat:@"firstname == %@ AND lastname == %@", @"James", @"Smith"];

NSError *error = nil;
self.scoresArray = [self.managedObject executeFetchRequest:fetchRequest error:&error];

if ([self.scoresArray count]) {

    Student *student = [self.scoresArray objectAtIndex:0];
    NSSet *score = student.scores;
    NSArray *arr = [score allObjects];
    NSLog(@"%@", [arr objectAtIndex:0]);
}

if I can directly access the Score entity instead of using NSSet, that would be ideal that way I can reference it using a dot notation. Any help would be appreciated. Thanks

Was it helpful?

Solution

Use something like the following:

AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
self.managedObjectContext = delegate.managedObjectContext;

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Student"];
    fetchRequest.predicate = [NSPredicate predicateWithFormat:@"firstname == %@ AND lastname == %@", @"James", @"Smith"];

NSError *error = nil;
NSArray *studentArray = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];

for (Student *student in studentArray) {

    Student *student = [self.studentArray objectAtIndex:0];

    NSLog(@" student is %@ %@", student.firstname, student.lastname);

    for (Score *score in student.scores) {
       // Do something with score
      NSLog(@"   score is %@", score);
    }
}

OTHER TIPS

Because Student has to-many relationship to Scores (and the property for it is scores), when you get the value of student.scores, it returns an unordered collection, which is NSSet in Foundation. So you just work with it like you work with NSSet and with collections in general.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top