I have the following tables in Core Data:
Cinema (movies) Movie (title, times) DateTime (startTime, endTime)
Basically there are several cinemas, each cinema can have several movies, also each movie can be shown in different cinemas, lastly each movie can have several show times(DateTime)
when I want to insert a movie into the database, I know its title and show time(startDate, endDate), I need to know if the movie is already in开发者_如何学运维 database, so what I do is:
- (BOOL)movieExistsInDB:(NSString *)title StartDate:(NSDate *)startDate EndDate:(NSDate *)endDate {
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
NSEntityDescription *entity =
[NSEntityDescription entityForName:@"Movie"
inManagedObjectContext:self.context];
[request setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:
@"title LIKE %@ AND timetable.startDate == %@ AND timetable.endDate == %@",
title,
startDate,
endDate];
[request setPredicate:predicate];
NSError *error = nil;
NSUInteger count = [context countForFetchRequest:request error:&error];
if (!error) {
return count > 0;
}
return NO;
}
it does not seem to work, so what is the problem?
Thanks!
edit: error message: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'to-many key not allowed here'
I think one of your attributes you are looking for is a one-to-many relation. So core data see's a NSSet instead of an NSObject. If you want to query through NSSet's you need "ANY" in your Fetchrequest. For instance:
...AND ANY timetable.startDate ...
If you want to know whether or not there's a Movie
entity for a given title, you don't need the dates in your predicate.
精彩评论