2009-11-20 123 views
1

我有一個日曆數量,每個日曆都有許多事件。我想查找日期> x的日曆的所有事件。一對多關係iPhone - NSPredicate核心數據查詢

我的方法簽名看起來像這樣

-(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

我改變了這種關係更名爲「事件」,並嘗試了以下

.... 
    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:]:該類不是關鍵事件編碼的關鍵值。'

回答

4

的幾點思考:

  1. 在你的模型中,newRelationship真的叫calendar
  2. 要重命名Eventsevents遵循命名約定(如EventCalendar實體資本,而像discipline屬性和關係就像events是小寫)
  3. 線了calendarevents關係是雙向

那說和做,你可以使用一個謂語,如:

- (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編程的一個很好的參考,蘋果的恰當名爲NSPredicate Programming Guide

+0

謝謝,所以你必須使用(名字像'%@')你不能使用對象ID作爲參考? – 2009-11-20 14:41:06