2

我正在将 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;
}

我将 date1 存储在 NSUserDefaults 中,如下所示:

NSDate *date1 = [[NSDate alloc] init];

[[NSUserDefaults standardUserDefaults] setObject:date1 forKey:@"date1"];

[[NSUserDefaults standardUserDefaults] synchronize];

该应用程序崩溃说 -[__NSCFString timeIntervalSinceReferenceDate]: unrecognized selector sent to instance。有人有想法么?

谢谢!

4

3 回答 3

6

要存储日期,请使用:

NSDate *myDate = [NSDate date];
[[NSUserDefaults standardUserDefaults] setObject:myDate forKey:@"myDateKey"];
[[NSUserDefaults standardUserDefaults] synchronize];

并得到它使用这个:

NSDate *myDate = (NSDate *)[[NSUserDefaults standardUserDefaults] objectForKey:@"myDateKey"];
于 2012-12-18T10:47:50.540 回答
4

我已经编译了你的代码,它对我有用。这是它的外观:

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;
}

看看这是否适合你

于 2012-12-18T10:49:36.280 回答
0

只是有一个愚蠢的错误......

您尚未在 中指定日期date1,请使用

NSDate *date1 = [NSDate date];

要检索它,请使用,

NSLog(@"-> %@",[[NSUserDefaults standardUserDefaults]objectForKey:@"myDateKey"]);
于 2012-12-18T10:58:13.883 回答