【问题标题】:Getting stored values from NSSet which was fretched from core data as to-many从 NSSet 获取存储的值,这些值是从核心数据中提取出来的
【发布时间】:2014-01-27 08:51:24
【问题描述】:

我实际上是 iPhone 编程的新手,并且已经成功创建了一个应用程序,但我不知道如何检索存储在 NSSet 中的值。我在彼此相关的核心数据中有 2 个实体。用户一对多得分。 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,那将是理想的方式,我可以使用点符号来引用它。 任何帮助,将不胜感激。谢谢

【问题讨论】:

    标签: core-data xcode5


    【解决方案1】:

    使用类似以下的内容:

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

    【讨论】:

    • 感谢您的帮助。我能够检索分数值。但是,我的问题是,当检索值时,它们是以 NSSet 数据类型检索的,我需要的是获取布尔类型。
    • 你的技术奏效了,现在也奏效了。我也可以检索布尔值。非常感谢您的帮助
    • @EdwardB。如果它有效,您应该通过单击对勾来接受答案。
    【解决方案2】:

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

    【讨论】:

    • 感谢您的帮助。我能够检索分数值。但是,我的问题是,当检索值时,它们的数据类型是 NSSet,我需要的是获取布尔类型。
    • 你需要一个布尔值的集合吗?您写道,从 User 到 Scores 的关系是一对多的关系。
    • 这种关系是对许多实体的,很少有实体具有接受布尔值的属性。我保存了这些布尔值,但无法将它们作为布尔值检索。实际上,我在 Ducan 的帮助下才开始使用它。如果您有与 Ducan 所展示的方法不同的方法,我很乐意看到。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-27
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    • 2018-04-07
    相关资源
    最近更新 更多