我有一个像这样的核心数据对象:
我建立一个谓词,以获得我需要获得电影和剧院的预定时间和每个选择时间
随着时间表的价值我试图去剧院
这是我的代码:
NSString *nameOfMovie = [[scheduleResults movie] valueForKey:@"nameOfMovie"];
NSPredicate *theaterPredicate = [NSPredicate predicateWithFormat:@"SUBQUERY (showTimes, $x, $x.nameOfMovie == %@ AND $x.showTimes.showTimes == %@).@count > 0", nameOfMovie, showTimes];
但是我的谓词出现了这个错误:
这里不允许使用多个键
你们中的任何人都知道我的谓词出错了吗?
答案 0 :(得分:1)
我发现这个问题非常有趣,所以创建一个简单的游乐场,用swift来测试你的案例的子查询。我认为你错过了数据模型中的某些关系,如果你真的关心它,你应该用单数命名实体,如电影,日程表,剧院等更有意义,因为实体总是单一的,关联可以是单数或复数取决于一对多或一对一的关系。
以下是我提出的数据模型,
// a Movie can have multiple schedule and a schedule can have multiple movies at the same time
Schedule << ------- >> Movie
// a Movie can be running in multiple theater and a theater can have multiple movies
Movie << ------>> Theater
因此,基于上述关系,我创建了一个操场文件来创建一些夹具数据并进行游戏,
class Schedule: NSObject {
var showTime: NSDate!
var movies: [Movie]!
}
class Theater: NSObject {
var name: String!
var movies: [Movie]!
}
class Movie: NSObject {
var nameOfMovie: String!
var theaters: [Theater]!
var showTimes: [Schedule]!
}
let hitech = Theater()
hitech.name = "Hitech Cinema"
let kino = Theater()
kino.name = "Kino"
let warner = Theater()
warner.name = "Warners"
let interstellar = Movie()
interstellar.nameOfMovie = "Interstellar"
let gravity = Movie()
gravity.nameOfMovie = "Gravity"
let wrathOfSpace = Movie()
wrathOfSpace.nameOfMovie = "Wrath of Space"
let today = NSDate()
let yesterday = today.dateByAddingTimeInterval(-60 * 60 * 24)
let tomorrow = today.dateByAddingTimeInterval(60 * 60 * 24)
let todaySchedule = Schedule()
todaySchedule.showTime = today
let yesterdaySchedule = Schedule()
yesterdaySchedule.showTime = yesterday
let tomorrowSchedule = Schedule()
tomorrowSchedule.showTime = tomorrow
todaySchedule.movies = [interstellar, gravity]
tomorrowSchedule.movies = [interstellar, wrathOfSpace]
yesterdaySchedule.movies = [wrathOfSpace, gravity]
interstellar.showTimes = [todaySchedule, tomorrowSchedule]
gravity.showTimes = [todaySchedule, yesterdaySchedule]
wrathOfSpace.showTimes = [tomorrowSchedule, yesterdaySchedule]
interstellar.theaters = [kino, hitech]
gravity.theaters = [kino, warner]
wrathOfSpace.theaters = [warner, hitech]
kino.movies = [interstellar, gravity]
hitech.movies = [interstellar, wrathOfSpace]
warner.movies = [wrathOfSpace, gravity]
let theaters:NSArray = [hitech, warner, kino]
var nameOfMovie = "Gravity"
var date = yesterday
var predicate = NSPredicate(format: "SUBQUERY(movies, $a, $a.nameOfMovie = %@ and SUBQUERY($a.showTimes, $b, $b.showTime = %@).@count > 0).@count > 0", nameOfMovie, date)
let threatersYesterdayGravity = theaters.filteredArrayUsingPredicate(predicate)
nameOfMovie = "Interstellar"
date = tomorrow
predicate = NSPredicate(format: "SUBQUERY(movies, $a, $a.nameOfMovie = %@ and SUBQUERY($a.showTimes, $b, $b.showTime = %@).@count > 0).@count > 0", nameOfMovie, date)
let threatersTomorrowInterstellar = theaters.filteredArrayUsingPredicate(predicate)
结果如我所料。您还可以使用上述关系,子查询符合您的需要。