經過幾個小時的搜索我已經想出了整個場景。 在這裏你有幾個解決方案;首先是更「骯髒」,因爲這是我第一次提出,而第二個是更優雅。無論如何,我會離開他們,因爲他們都可以派上用場。
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