经过几个小时的搜索我已经想出了整个场景。 在这里你有几个解决方案;首先是更“肮脏”,因为这是我第一次提出,而第二个是更优雅。无论如何,我会离开他们,因为他们都可以派上用场。
S 0吕T I O 4 N - 1
由于mit3z我可以把拼在一起,以找出一个解决方案的帮助。
正如他指出的,可以实现此方法插入NSObject的类别:
- (NSArray *)c_propertyNames;
(看他这部分的代码响应,并进一步有关它的更多细节)
这给我冒昧地做这样的事情:
- (void) addLocation {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"/Locations.plist"];
NSArray *keys = [curLocation c_propertyNames]; // retrieve all the keys for this obj
NSDictionary *values = [self.curLocation dictionaryWithValuesForKeys:keys];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
for(NSString *key in keys) {
NSString *aaa = [NSString stringWithFormat:@"%@", (NSString *)[values valueForKey:key]];
[dict setValue:aaa forKey:key];
}
[dict writeToFile:path atomically:YES];
}
需要for循环此Superdumb在NSDictionary中所有的数据转换成NSString的,使他们可以写入T他可以毫不费力地提交文件,如果你只是制作字典,然后尝试立即保存,你就不会成功。
通过这种方式,我可以将所有CLLocation对象“序列化”为一个字典,然后写入一个plist文件。
S 0吕T I 0:N - 2
,我想出了这样做的一个非常简单(和更优雅)的方法:使用NSCoding。 因为事实(我才发现)的CLLocation数据类型符合NSCoding,您可以通过的NSKeyedArchiver调用数据归档获得一个blob描述你的阵列,然后将其直接存储到plist中,这样的:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"/Locations.plist"];
NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
[data setValue:[NSKeyedArchiver archivedDataWithRootObject:arrayOfLocations] forKey:@"LocationList"];
[data writeToFile:path atomically:YES];
[data release];
and voila'。就那么简单! :)
基础上,你可以很容易地回到你的数据相同的原则,通过NSKeyUnarchiver:
self.arrayOfLocations = [[NSMutableArray alloc] initWithArray:[NSKeyedUnarchiver unarchiveObjectWithData: (NSData *)[dict objectForKey:@"LocationList"]]];
类别代码运行良好:它填充“键”NSArray,但只要我执行[dict writeToFile:path automatically:YES];没有任何文件写在文件上。如果你想,我用相对代码更新了我的问题。谢谢! – holographix 2012-04-19 21:02:25
好吧我已经做了更多的实验,我发现如果我在NSDictionary中包含键“clientLocation”的元素,它将不会写入plist文件,否则它就像魅力一样。也许这是由于该字段是一个字符串有很多字符的事实引起的。这是该元素的内容:<00000000 ffff0000 94092907 20413b40 6a5c4eeb 797455c0 a6f71fc4 7fde7d40 00000000 00000000 00000000 0000f0bf 00000000 0000f0bf 00000000 0000f0bf 00000000 0000f0bf 00000000 0000f0bf 00000000 0000f0bf 00000000 0000f0bf bc043f09 c140b541 64000000 00000000 00000040 00000000> – holographix 2012-04-19 21:57:23
好神秘解决了,我不得不通过循环解析数据。我会发布另一个解决方案,将我的代码与您的代码结合在一起。 – holographix 2012-04-19 22:08:15