我有一个将 NSArray 中的时间存储为 NSString 的对象。我选择了 NSString,因为那是我最终显示的而不是 NSDate。我正在尝试为它设置一个 UILocalNotification 。我所做的是:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.timeZone = [NSTimeZone systemTimeZone];
dateFormatter.dateFormat = @"h:mm a";
for (NSString *s in _times) {
NSDate *date = [dateFormatter dateFromString:s];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
fromDate:date];
NSDateComponents *timeComponents = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:date];
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:[dateComponents day]];
[dateComps setMonth:[dateComponents month]];
[dateComps setYear:[dateComponents year]];
[dateComps setHour:[timeComponents hour]];
[dateComps setMinute:[timeComponents minute]];
NSDate *itemDate = [calendar dateFromComponents:dateComps];
NSLog(@"%@", [dateFormatter stringFromDate:itemDate]);
UILocalNotification *note = [[UILocalNotification alloc] init];
note.alertAction = thePill.name;
note.alertBody = thePill.note;
note.fireDate = itemDate;
note.timeZone = [[NSCalendar currentCalendar] timeZone];
if (note.fireDate == nil) {
NSLog(@"nil firedate");
}
// note.repeatInterval = NSDayCalendarUnit;
NSData *data = [self archivePill:thePill];
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:data forKey:PILL_NOTIFICATION];
note.userInfo = infoDict;
[[UIApplication sharedApplication] scheduleLocalNotification:note];
}
当我 NSLog itemDate 时间时,这就是我想要的。在方法结束时,本地通知会立即触发。我不确定为什么,因为我的日期是正确的时间,我以为我只是将 fireDate 设置为那个日期?谢谢。