我正在用一小段代码比较date1和date2,并收到崩溃通知。
我在NSUserDefaults中获得date1:
NSDate *date1 = [[NSUserDefaults standardUserDefaults]
objectForKey:@"date1"];
NSDate *date2 = [[NSDate alloc] init];
if (fabs([date2 timeIntervalSinceDate:date1]) < 60)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"60 seconds or less" message:@"Text" delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles:nil, nil];
[alert show];
return;
}
我在NSUserDefaults中存储date1,如下所示:
NSDate *date1 = [[NSDate alloc] init];
[[NSUserDefaults standardUserDefaults] setObject:date1 forKey:@"date1"];
[[NSUserDefaults standardUserDefaults] synchronize];
应用程序崩溃说 - [__ NSCFString timeIntervalSinceReferenceDate]:发送到实例的无法识别的选择器。有人有什么想法吗?
谢谢!
答案 0 :(得分:4)
要存储日期,请使用此:
NSDate *myDate = [NSDate date];
[[NSUserDefaults standardUserDefaults] setObject:myDate forKey:@"myDateKey"];
[[NSUserDefaults standardUserDefaults] synchronize];
并且要使用它:
NSDate *myDate = (NSDate *)[[NSUserDefaults standardUserDefaults] objectForKey:@"myDateKey"];
答案 1 :(得分:2)
我编译了你的代码,它对我有用。这是它的外观:
NSDate *date1test = [[NSDate alloc] init];
[[NSUserDefaults standardUserDefaults] setObject:date1test forKey:@"date1"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSDate *date1 = [[NSUserDefaults standardUserDefaults]
objectForKey:@"date1"];
NSDate *date2 = [[NSDate alloc] init];
if (fabs([date2 timeIntervalSinceDate:date1]) < 60)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"60 seconds or less" message:@"Text" delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles:nil, nil];
[alert show];
return;
}
看看这是否为你编译
答案 2 :(得分:0)
只是一个愚蠢的错误......
您尚未在date1
中指定日期,请使用
NSDate *date1 = [NSDate date];
要检索它,请使用
NSLog(@"-> %@",[[NSUserDefaults standardUserDefaults]objectForKey:@"myDateKey"]);