我有一些日历,每个日历都有很多事件。我想找到日期>的日历的所有事件。 X
我的方法签名看起来像这样
-(NSArray*)eventsForCalender:(Calendar*)calender StartDate:(NSDate*)start endDate:(NSDate*)endDate;
我在这样的日历中添加了一个事件,但我不知道如何为查询构建NSPredicate。任何帮助表示赞赏
-(Event*)newEventforCalender:(Calendar*)calender
{
Event * newEvent = (Event*)[NSEntityDescription insertNewObjectForEntityForName:@"Event" inManagedObjectContext:app.managedObjectContext];
NSMutableSet * eventsArray = [calender mutableSetValueForKey:@"Events"];
[eventsArray addObject:newEvent];
[app.managedObjectContext processPendingChanges];
return newEvent;
}
alt text http://img4.imageshack.us/img4/5218/screenshot20091120at140.png
我将关系名称更改为“events”并尝试以下
....
NSEntityDescription * entity = [NSEntityDescription entityForName:@"Calendar" inManagedObjectContext:app.managedObjectContext];
[request setEntity:entity];
NSPredicate * predictate = nil;
predictate = [NSPredicate predicateWithFormat:@"(name == %@) AND (Event.start > '%@') AND (Event.finish < '%@')", calender.name, start, endDate, nil];
[request setPredicate:predictate];
...
但是我得到了例外
由于未捕获的异常'NSUnknownKeyException'而终止应用程序,原因:'[valueForUndefinedKey:]:此类不是键事件的键值编码兼容。'
答案 0 :(得分:4)
一些想法:
newRelationship
真的称为calendar
吗? Events
重命名为events
以遵循命名惯例(Event
和Calendar
等实体大写,而像discipline
这样的属性和类似的关系events
是小写的)calendar
和events
关系说完了,你可以使用类似的谓语:
- (NSArray *) eventsForCalendar:(Calendar *)calendar startDate:(NSDate *)startDate endDate:(NSDate *)endDate {
NSPredicate *_predicate;
NSString *_predicateStr;
NSSet *_calendarQueryResults;
_predicateStr = [NSString stringWithFormat:@"(name like '%@') AND (event.start > '%@') AND (event.finish < '%@')", calendar.name, startDate, endDate];
_predicate = [NSPredicate predicateWithFormat:_predicateStr];
_calendarQueryResults = [_managedObjectContext fetchObjectsForEntityName:@"Calendar" withPredicate:_predicate];
return [_calendarQueryResults allObjects];
}
如果日历名称足以唯一标识单个日历,则此功能将起作用。如果您有两个具有相同名称的日历,则必须添加其他搜索条件,例如@"(category like '%@') ... ", calendar.category, ...
您还可以使用对象ID:
_predicateStr = [NSString stringWithFormat:@"(SELF == %@) AND (event.start > '%@') AND (event.finish < '%@')", calendar, startDate, endDate];
NSPredicate
编程的一个很好的参考是Apple恰当地命名为NSPredicate Programming Guide
。