Tôi có thuộc tính NSDate
được gọi là startDate
được lưu trữ trong cửa hàng lưu giữ ở định dạng sau (hình bên dưới).iOS: NSPredicate sử dụng NSDate để so sánh
426.174.354 = 04 tháng bảy năm 2014
tôi cần phải tạo (3) NSFetchRequest
sử dụng các vị từ.
Đối startDate
:
fetchRequest1
sử dụng ngữ (s) cần phải lấy tất cả những gì rơi vào ngày hôm nay dựa trên thời gian thiết bị của người dùng.fetchRequest2
sử dụng vị từ cần tìm nạp mọi thứ trong quá khứ, có nghĩa là ngày hôm qua và trước đó, dựa trên thời gian thiết bị của người dùng.fetchRequest3
sử dụng vị từ cần tìm nạp mọi thứ trong tương lai, có nghĩa là bắt đầu từ ngày mai và sau đó, dựa trên thời gian của thiết bị của người dùng.
Dưới đây là đoạn code tôi có cho đến nay:
-(NSMutableArray *)getFetchPredicate:(NSUInteger)fetchRequestType
{
NSDate *now = [self getcurrentTime:[NSDate date]];
NSDateFormatter *format = [[NSDateFormatter alloc] init];
format.dateFormat = @"dd-MM-yyyy";
format.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
NSString *stringDate = [format stringFromDate:now];
NSDate *todaysDate = [format dateFromString:stringDate];
//today's date is now a date without time.
NSMutableArray *subpredicates;
if (fetchRequestType == 1)
{
NSPredicate *subPredToday = [NSPredicate predicateWithFormat:@"startDate == %@ ", todaysDate];
[subpredicates addObject:subPredToday];
}
else if (fetchRequestType == 2)
{
NSPredicate *subPredPast = [NSPredicate predicateWithFormat:@"startDate < %@", todaysDate];
[subpredicates addObject:subPredPast];
}
else if (fetchRequestType == 3)
{
NSPredicate *subPredFuture = [NSPredicate predicateWithFormat:@"startDate > %@", todaysDate];
[subpredicates addObject:subPredFuture];
}
return subPredicates;
}
-(NSDate *)getcurrentTime:(NSDate*)date
{
NSDate *sourceDate = date;
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* deviceDateWithTime = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate];
return deviceDateWithTime;
}
Đoạn mã trên là không tìm nạp các đối tượng ngay từ CoreData. Tôi có cảm giác rằng các vị từ của tôi để so sánh là không chính xác. Tôi không chắc chắn cách chuyển đổi thời gian được lưu trữ ở dạng startDate
thành chỉ định dạng Ngày và áp dụng điều đó trong Dự phòng để so sánh. Bất kỳ đề xuất?
Không có loại yêu cầu tìm nạp nào trả về kết quả chính xác? – spassas
Không. Tôi có cần phải chuyển đổi ngày được lưu trữ thành chỉ ngày không? – user1107173