我有一个大问题。 我的程序必须保存一个Xml文件,其中包含3个浮点值(加速度计的x,y,z)和NSString值(名称)。 我能怎么做? 非常感谢
答案 0 :(得分:1)
如果您对XML格式没有特定要求,则可以使用NSKeyedArchiver类以XML格式存档数据:
float x, y, z;
NSString *name;
NSMutableData *data = [NSMutableData data];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver setOutputFormat:NSPropertyListXMLFormat_v1_0];
[archiver encodeFloat:x forKey:@"x"];
[archiver encodeFloat:y forKey:@"y"];
[archiver encodeFloat:z forKey:@"z"];
[archiver encodeObject:name forKey:@"name"];
[archiver finishEncoding];
BOOL result = [data writeToFile:@"MyFile" atomically:YES];
[archiver release];
写完后,阅读很简单:
NSData *data = [NSData dataWithContentsOfFile:@"MyFile"];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
x = [unarchiver decodeFloatForKey:@"x"];
y = [unarchiver decodeFloatForKey:@"y"];
z = [unarchiver decodeFloatForKey:@"z"];
name = [unarchiver decodeObjectForKey:@"name"];
[unarchiver finishDecoding];
[unarchiver release];