我使用transient属性将核心数据对象分类到单独的表视图部分。它被称为'sectionIdentifier'。此属性的getter位于NSManagedObject subclass
内,名为ToDoItem.m
。问题是在应用程序执行期间,新添加的对象始终显示在“今日”部分下。在新推出应用程序后,所有对象都显示在预期的行下。专家用户告诉我,在设置新对象时,sectionIdentifier必须无效,但我不知道如何使其无效。这是我的NSManagedObject子类代码:
#import "ToDoItem.h"
#import "ToDoGroup.h"
#import "ToDoSubItem.h"
@implementation ToDoItem
@dynamic todoDescription;
@dynamic todoName;
@dynamic todoDueDate;
@dynamic sectionIdentifier;
@dynamic todogroup;
@dynamic todosubitems;
-(NSString *)sectionIdentifier{
[self willAccessValueForKey:@"sectionIdentifier"];
NSString *tmp = [self primitiveValueForKey:@"sectionIdentifier"];
[self didAccessValueForKey:@"sectionIdentifier"];
if (!tmp){
NSDate *date = self.todoDueDate;
NSDate *todayDate = [NSDate date];
NSLog(@"date= %@",date);
NSLog(@"todayDate = %@",todayDate);
NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger comps = (NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit);
NSDateComponents *date1Components = [calendar components:comps fromDate:date];
NSDateComponents *date2Components = [calendar components:comps fromDate:todayDate];
date = [calendar dateFromComponents:date1Components];
todayDate = [calendar dateFromComponents:date2Components];
if([date
compare:todayDate] == NSOrderedSame) {
tmp = @"1";//TODAY
}
else if([date
compare:todayDate] == NSOrderedDescending){
tmp = @"2";//OVERDUE
}
else if ([date
compare:todayDate] == NSOrderedAscending){
tmp =@"0";//UPCOMING
}
NSLog(@"Tmp= %@",tmp);
[self setPrimitiveValue:tmp forKey:@"sectionIdentifier"];
}
return tmp;
}
@end
欢迎任何帮助......
答案 0 :(得分:2)
问题是部分标识符是从todoDueDate
计算的和缓存,但在todoDueDate
更改时不会自动更新。
DateSectionTitles/APLEvent.m Apple的示例代码显示了如何实现这样的自动更新。
在您的情况下,您应该将以下方法添加到托管对象子类
ToDoItem
:
- (void)setTodoDueDate:(NSDate *)newDate
{
// If the todoDueDate changes, the section identifier become invalid.
[self willChangeValueForKey:@"todoDueDate"];
[self setPrimitiveValue:newDate forKey:@"todoDueDate"];
[self didChangeValueForKey:@"todoDueDate"];
// Set the section identifier to nil, so that it will be recalculated
// when the sectionIdentifier method is called the next time:
[self setPrimitiveValue:nil forKey:@"sectionIdentifier"];
}
+ (NSSet *)keyPathsForValuesAffectingSectionIdentifier
{
// If the value of todoDueDate changes, the section identifier may change as well.
return [NSSet setWithObject:@"todoDueDate"];
}