Converting NSDate to NSString causes unrecognized

2019-02-28 17:02发布

问题:

I am storing an NSDate in a plist as a string, and at launch I am trying to convert the string from the plist back to an NSDate to compare it later.

This is how I am storing the value in my plist:

[InfoDic setValue:[NSDate date] forKey:@"LastDate"];

In the log (When I convert the [NSDate date] to a proper string) it says this:

2013-04-13 22:47:57 +0000

This is how I am trying to convert the plist value back to an NSDate:

NSString *Checkdate= [InfoDic objectForKey:@"LastDate"];
NSDateFormatter *DateFormat=[[NSDateFormatter alloc]init];
[DateFormat setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
NSDate *theday=[DateFormat dateFromString:Checkdate];

This is the error log on my iPhone 4S:

<Error>: -[__NSDate length]: unrecognized selector sent to instance 0x1d8715e0
<Error>: *** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '-[__NSDate length]: unrecognized selector sent to instance 0x1d8715e0'
    *** First throw call stack:
(0x31e5c2a3 0x39b7997f 0x31e5fe07 0x31e5e531 0x31db5f68 0x327c213d 0x327c208d 0x327c237b 0x23fe1 0x33c83595 0x33cc3d79 0x33cbfaed 0x33d011e9 0x2385d 0x33cc4ad9 0x33cc4663 0x33cbc84b 0x33c64c39 0x33c646cd 0x33c6411b 0x3597a5a3 0x3597a1d3 0x31e31173 0x31e31117 0x31e2ff99
0x31da2ebd 0x31da2d49 0x33cbb485 0x33cb8301 0x235a1 0x23528)

Please note that when I install the app on my device it takes the first date and stores it in the plist. When I close the app and rerun it, it gives me the SIGABRT.

What should I do about this?

回答1:

You are overcomplicating things. What makes you think that storing a NSDate object you'll get back a NSString?

Just do

NSDate * checkDate = [InfoDic objectForKey:@"LastDate"];

Also, don't confuse KVC methods with NSDictionary methods.

You want to use setObject:forKey: instead of setValue:forKey if you don't want to face bad surprises.



回答2:

You are not storing a date as a string in the plist, you are storing it as a date.

The line:

[InfoDic setValue:[NSDate date] forKey:@"LastDate"];

stores the actual NSDate object.

All you need to get it back out is to call:

NSDate *theDay = InfoDic[@"LastDate"];

BTW - the line:

[InfoDic setValue:[NSDate date] forKey:@"LastDate"];

should be:

[InfoDic setObject:[NSDate date] forKey:@"LastDate"];

or just:

InfoDic[@"LastDate"] = [NSDate date];