【发布时间】:2014-06-02 10:05:09
【问题描述】:
我想通过从今天开始搜索并排除核心数据请求提供的日期来获得下一个可用日期。
我的初始化代码,以及在同一个类中实现的帮助方法
+ (NSDate *)getDateByAddingDays:(NSInteger)days toDate:(NSDate *)date {
NSDate *newdate = [[NSDate alloc]init];
if (days != 0) {
NSDateComponents *components = [[NSDateComponents alloc] init];
components.day = days;
NSCalendar *calendar = [NSCalendar currentCalendar];
newdate = [calendar dateByAddingComponents:components toDate:date
options:0];
}
return newdate;
}
+ (void)myTroublesomeMethod {
// standard initialization of NSFetchRequest
NSManagedObjectContext *context = [(id)[[UIApplication sharedApplication] delegate] managedObjectContext];
NSDate *today = [NSDate date];
NSFetchRequest *request3 = [[NSFetchRequest alloc] init];
NSEntityDescription *chiusureDescription = [NSEntityDescription entityForName:@"Chiusure" inManagedObjectContext:context];
NSError *error;
[request3 setEntity:chiusureDescription];
NSArray *arrayChiusure = [context executeFetchRequest:request3 error:&error];
// I then extract the "data" attribute, that stores the date to be excluded
NSMutableArray *giorniChiusura = [[NSMutableArray alloc]init];
for (Chiusure *entity in arrayChiusure) {
[giorniChiusura addObject:(NSDate*) entity.data];
}
// and here is where the problem rises:
NSInteger days = 0;
NSDate *nextDate = [self getDateByAddingDays:days toDate:today];
if ([arrayChiusure containsObject:nextDate]) {
// HERE is the error, I suppose. nextDate is never contained in arrayChiusure, so the next while statement is an infinite loop.
while ([arrayChiusure containsObject:nextDate]) {
days += 1;
nextDate = [self getDateByAddingDays:days toDate:today];
}
// OMITTED: use of nextDate somewhere later in my code
}
我想到的替代方法:
- 我知道我可以在
while中创建一个新的NSFetchRequest循环以检查建议的 nextDate 是否包含在Chiusure实体数据集,但对我来说似乎有点矫枉过正。
附加信息:
-
arrayChiusure预计最多包含 10-20 个实体 - 我认为该错误与错误比较有关(即在
[arrayChiusure containsObject:nextDate]中),但我不明白为什么
任何帮助表示赞赏:) 提前致谢
【问题讨论】:
-
1)
entity.data是什么类型,为什么必须将其转换为NSDate *? - 2) 你知道NSDate不仅代表“日”,而且代表一个绝对时间点(包括小时、分钟、秒和毫秒)。因此数组包含nextDate的可能性非常低。 -
@MartinR 我将其转换为
NSDate只是为了让您知道这是一个NSDate否则没有必要......简单的懒惰是为了不必解释我的全部核心数据实体定义 :#) 但是你是对的:我可以强制nextDate将小时、分钟、秒 = 设为 0 以匹配entity.data,因为它是使用 RestKit 从 JSON“纯”日期数组填充的.
标签: ios objective-c core-data nsdate nsfetchrequest