在NSUserDefaults中保存日期(作为NSString)不起作用

时间:2011-04-14 13:24:26

标签: objective-c datetime ios4 nsuserdefaults

我正在尝试在NSUSerDefaults中保存这个日期:

2011-04-14T13:18:25+0000

但我不想要最后一位(+0000),所以我用这种方法把它砍掉了:

NSString *since = [last objectForKey:@"updated_time"];
NSString *cutOff = @"+0000"; 
NSRange range = [since rangeOfString:cutOff];
self.lastUpdated = [since substringToIndex:range.location];
[[NSUserDefaults standardUserDefaults] setObject:lastUpdated forKey:@"lastUpdated"];

正如您所看到的,这只是一个非常简单的操作,会将上面的字符串切换为:

2011-04-14T13:18:25

然而,当我从NSUserDefaults加载它时,我得到了这个:

2011-04-14 13:18:25 +0000

谁能告诉我为什么?

更新:

我像往常一样在.h:

中声明了lastUpdated
@interface TwitModel
{
    NSString *lastUpdated;
}

@property (retain) NSString *lastUpdated;

in .m:

@synthesize lastUpdated;

当我想加载它时:

    if(self.lastUpdated == nil) {
        self.lastUpdated = [[NSUserDefaults standardUserDefaults] objectForKey:@"lastUpdated"];
    }

2 个答案:

答案 0 :(得分:1)

您需要在synchronize上致电NSUserDefaults,以便正确保存数据:

[[NSUserDefaults standardUserDefaults] synchronize];

修改

这是我的工作代码:

// Output previous launch's stored value
NSLog(@"Value From Previous Launch: %@", [[NSUserDefaults standardUserDefaults] valueForKey:@"lastUpdated"]);

NSString *since = @"2011-04-14T13:18:25+0000";
NSLog(@"Since: %@", since);
NSString *cutOff = @"+0000"; 
NSRange range = [since rangeOfString:cutOff];
NSString* lastUpdated = [since substringToIndex:range.location];
[[NSUserDefaults standardUserDefaults] setObject:lastUpdated forKey:@"lastUpdated"];
[[NSUserDefaults standardUserDefaults] synchronize];

NSLog(@"Value: %@", [[NSUserDefaults standardUserDefaults] valueForKey:@"lastUpdated"]);

输出:

2011-04-14 08:52:29.972 TestApp[2117:207] Value From Previous Launch: 2011-04-14T13:18:25
2011-04-14 08:52:29.973 TestApp[2117:207] Since: 2011-04-14T13:18:25+0000
2011-04-14 08:52:29.975 TestApp[2117:207] Value: 2011-04-14T13:18:25

答案 1 :(得分:0)

很难说 - 你能告诉我们重新加载价值的代码吗?如果使用日期格式化程序以您想要的格式生成字符串,那么至少在概念上可能更简单。或者,只需保存日期本身,并担心在需要显示日期时将其格式化。