我实际上是 iPhone 编程新手,并且已经成功创建了一个应用程序,但我不知道如何检索存储在 NSSet 中的值。我的核心数据中有两个相互关联的实体。用户一对多到分数。Users 实体具有 firsNname 和 lastName 属性,Scores 实体具有 onTime、wasAbsent 和 dateIn 属性。我使用基于firstName 和lastName 的谓词进行获取,然后执行获取。提取成功,我能够在一次提取调用中获取两个实体。但是我无法从 Scores 实体获取值。无论我做什么,它总是返回 NSSet 对象。我想要做的是检索存储在 onTime 和 wasAbsent 属性中的布尔值并将它们提供给 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]);
}

如果我可以直接访问 Score 实体而不是使用 NSSet,那将是理想的方式,我可以使用点符号引用它。任何帮助,将不胜感激。谢谢

有帮助吗?

解决方案

使用以下内容:

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);
    }
}
.

其他提示

因为 Student 与 Scores 具有多对关系(并且它的属性是 scores),当你得到的值 student.scores, ,它返回一个无序集合,即Foundation中的NSSet。因此,您只需像使用 NSSet 和一般集合一样使用它即可。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top