Ios 如何使用核心数据关系?
在我的应用程序中,我有3个相关实体。运动员、运动和运动分数 运动员与运动有着千丝万缕的联系。与之相反的是谁的事业。 运动与运动成绩有着多方面的关系。这与运动的方向相反Ios 如何使用核心数据关系?,ios,objective-c,cocoa-touch,core-data,Ios,Objective C,Cocoa Touch,Core Data,在我的应用程序中,我有3个相关实体。运动员、运动和运动分数 运动员与运动有着千丝万缕的联系。与之相反的是谁的事业。 运动与运动成绩有着多方面的关系。这与运动的方向相反 NSMutableArray *allScores = [NSMutableArray arrayWithCapacity:0];; for (Exercise *exercise in athleteExercises) { if ([exercise.scores count]>0) { [allScor
NSMutableArray *allScores = [NSMutableArray arrayWithCapacity:0];;
for (Exercise *exercise in athleteExercises) {
if ([exercise.scores count]>0) {
[allScores addObjectsFromArray:[exercise.scores allObjects]; //exercise.scores must be NSSet type
}
}
我想执行一个获取请求,从中获取运动员的所有训练分数。我怎么才能得到呢?我是否需要运动员和运动成绩之间的另一种关系,或者这是多余的?如果是,我将如何使用运动作为我请求的谓词?如果运动与运动员有关系,那么您应该能够执行以下操作:
[NSPredicate predicateWithFormat:@"SELF.athlete = @%", currentAthlete];
然后就是:
[Exercise fetchByPredicate:currentAthletePredicate];
应该是这样。如果我清楚地理解,您需要为运动员选择所有的训练分数,但运动员与训练分数表没有直接关系 对此的SLQ查询可能如下所示:
Select *
from ExerciseScore
where IDScore in (select IDScore
from Exercise
where IDExercise in ( select IDExercise
from Athlete
)
)
但在核心数据中,您无法操作SLQ查询。
试试这种方法
1.为运动员获取所有训练:
NSError *error;
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Exercise"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.athlete = @%", currentAthlete];
request.predicate=predicate;
NSArray *athleteExercises = [self.managedObjectContext executeFetchRequest:request error:&error];
2.迭代整个练习数组,以获得每个练习的所有练习分数
NSMutableArray *allScores = [NSMutableArray arrayWithCapacity:0];;
for (Exercise *exercise in athleteExercises) {
if ([exercise.scores count]>0) {
[allScores addObjectsFromArray:[exercise.scores allObjects]; //exercise.scores must be NSSet type
}
}
allScores
数组现在包含特定运动员的所有ExerciseScore
对象。
谓词可以具有关键路径:
@"whichExercise.whosExercise = %@",athlete
或者,如果您已经有了运动员,则不要执行获取请求,只需通过关系属性获取分数