Saving a date in NSUserDefaults (as NSString) not working
I'm trying to save this date in NSUSerDefaults:
2011-04-14T13:18:25+0000
But I don't want the last bit (+0000), so I chopped it off using this method:
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"];
As you can see, it's just a very simple operation that will chop the above string to this:
2011-04-14T13:18:25
However when I load this from NSUserDefaults, I get this:
2011-04-14 13:18:25 +0000
Can anyone tell me why?
UPDATE:
I declared lastUpdated as usual in .h:
@interface TwitModel
{
NSString *lastUpdated;
}
@property (retain) NSString *lastUpdated;
in .m:
@synthesize lastUpdated;
When I want to load it:
开发者_如何学Pythonif(self.lastUpdated == nil) {
self.lastUpdated = [[NSUserDefaults standardUserDefaults] objectForKey:@"lastUpdated"];
}
You need to call synchronize
on NSUserDefaults
in order for it to properly save the data:
[[NSUserDefaults standardUserDefaults] synchronize];
EDIT
Here's my working code:
// 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"]);
And the output:
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
It's hard to say -- can you show us the code that reloads the value? It might be simpler, conceptually at least, if you use a date formatter to produce a string in the format you want. Or, just save the date itself, and worry about formatting it when you need to display it.
精彩评论