Iphone 如何以编程方式获取NSDate plist表示形式?
由于plist是xml,即文本,因此当NSDate对象写入plist时,结果如下:Iphone 如何以编程方式获取NSDate plist表示形式?,iphone,objective-c,cocoa,plist,nsdate,Iphone,Objective C,Cocoa,Plist,Nsdate,由于plist是xml,即文本,因此当NSDate对象写入plist时,结果如下: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <date>2011-04-
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<date>2011-04-01T02:09:15Z</date>
</plist>
更复杂的是,上面的表示形式是GMT,显然时区是在创建NSDate对象的过程中设置的。我看到的上述代码的替代方法是获取GMT偏移量,在dateWithTimeInterval:sinceDate:
方法中使用它来获取GMT日期,然后使用NSDateFormatter
写出上述字符串。然而,因为这会带来更多的开销
有没有办法只获取该xml字符串?NSDate的
description
方法使用YYYY-MM-DD HH:MM:SS±HHMM格式返回一个字符串
编辑:executor21指出,以下部分仅对OS X有效,而不是对iOS有效
如果您不需要该格式,可以使用
descriptionWithCalendarFormat:timeZone:locale:
来定义您自己的格式。请参见如果您真的要创建只包含一个日期的属性列表,那么您发布的代码似乎是正确的选择。我知道你会怎么想那有点麻烦,但是您可以在NSDate上将其粘贴到类别中的方法中,这样您就可以直接从属性列表格式中读取或写入日期。在这种情况下,NSDateFormatter实际上是最好的选择--我需要在iOS 3.1.3及更高版本的设备上运行它,因此dataWithPropertyList:format:options:error:
method(在4.0中引入)不是选项,而
dataFromPropertyList:format:errorDescription:
计划弃用
此外,我在上面犯了一个错误:应该是这样的
NSString *xmlRepresentationOfCurrentDate = [[[[[[[NSString alloc] initWithData:[NSPropertyListSerialization dataWithPropertyList:self format:kCFPropertyListXMLFormat_v1_0 options:0 error:NULL] encoding:NSUTF8StringEncoding] autorelease] componentsSeparatedByString:@"<date>"] objectAtIndex:1] componentsSeparatedByString:@"</date>"] objectAtIndex:0];
descriptionWithCalendarFormat:timeZone:locale:
是一种Mac OS X方法,它在iOS上不存在。对不起,我以为苹果会同时提供这两种方法。我将编辑我的帖子来说明这一点。它也是“预定弃用”的,所以你不应该在任何一个平台上使用它。实际上你是对的,但主要问题是dataFromPropertyList:format:errorDescription:
是预定弃用和替换的方法,dataWithPropertyList:format:options:error:
仅在iOS 4.0及更高版本中可用。我需要我的代码在3.1.3及以上系统上运行。在这种情况下,NSDateFormatter是最好的选择(见下面我的答案)。那么为什么不测试-dataWithPropertyList:format:options:error:
,如果不可用,则返回到-dataFromPropertyList:format:errorDescription:
?
NSString *xmlRepresentationOfCurrentDate = [[[[[[[NSString alloc] initWithData:[NSPropertyListSerialization dataWithPropertyList:self format:kCFPropertyListXMLFormat_v1_0 options:0 error:NULL] encoding:NSUTF8StringEncoding] autorelease] componentsSeparatedByString:@"<date>"] objectAtIndex:1] componentsSeparatedByString:@"</date>"] objectAtIndex:0];
-(NSString *)xmlRepresentation{
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setTimeStyle:NSDateFormatterFullStyle];
[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
return [[formatter stringFromDate:self] stringByAppendingString:@"Z"];
}