在实施日期选择器后,我在Xcode中遇到了一个非常令人沮丧的错误。调试器中的错误是:“因未捕获的异常而终止应用程序'NSInternalInconsistencyException',原因:'无效的参数不满足:日期”
我几个小时以来一直在查看我的代码,但找不到问题。这可能是因为我没有检查nil,第一次安装和启动应用程序时没有日期,因此可能导致崩溃。如果是,我如何在此代码中检查nil?我在编程方面还很新,任何帮助都会非常感激。这是代码:
#import "DatePickerViewController.h"
@implementation DatePickerViewController
@synthesize datePicker;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Initialization code
}
return self;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"mm'/'dd'/'yyyy"];
NSDate *eventDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"DatePickerViewController.selectedDate"];
localNotif.fireDate = [eventDate dateByAddingTimeInterval:-13*60*60];
localNotif.timeZone = [NSTimeZone defaultTimeZone];
localNotif.alertBody = @"Tomorrow!";
localNotif.alertAction = nil;
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 0;
[[UIApplication sharedApplication]presentLocalNotificationNow:localNotif];
return YES;
}
- (void)viewDidLoad {
NSDate *storedDate = [[NSUserDefaults standardUserDefaults]
objectForKey:@"DatePickerViewController.selectedDate"];
[self.datePicker setDate:storedDate animated:NO];
}
- (IBAction)dateChanged:(id)sender {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDate *selectedDate = [self.datePicker date];
[defaults setObject:selectedDate forKey:@"DatePickerViewController.selectedDate"];
}
答案 0 :(得分:24)
在使用前,您不会检查日期是否为空,例如
(void)viewDidLoad {
NSDate *storedDate = [[NSUserDefaults standardUserDefaults]
objectForKey:@"DatePickerViewController.selectedDate"];
// add this check and set
if (storedDate == nil) {
storedDate = [NSDate date];
}
// ---
[self.datePicker setDate:storedDate animated:NO];
}
答案 1 :(得分:3)