将位置/ gps坐标写入文件

时间:2011-06-29 17:07:45

标签: iphone objective-c xcode location core-location

嗯,我知道这可能听起来很基本,但我确实一直在寻找无处可寻的答案。我试图在每次更新时将位置坐标保存到文件中 - 听起来很简单....我有两个问题:一个是数据类型(writeToFile似乎只保存NSData)而另一个是附加到文件的结尾。我试图使用NSKeyedArchiver,但它写了一堆垃圾,我找不到如何附加到文件的末尾。

这是我的代码 - 如果你能提供帮助,我会非常感激。谢谢!

....

NSMutableArray *array = [[NSMutableArray alloc] init];
NSNumber *numLat = [NSNumber numberWithFloat:location.coordinate.latitude];
NSNumber *numLong = [NSNumber numberWithFloat:location.coordinate.longitude];


[array addObject:numLat];    
[array addObject:numLong];    

NSFileHandle *file;
file = [NSFileHandle fileHandleForUpdatingAtPath: @"./location.txt"];

if (file == nil)
    NSLog(@"Failed to open file");


[file seekToEndOfFile];

[file writeData: array]; //BTW - this line doesn't work if I replace array with numLat which is an NSNumber - unlike what many people have said in various discussions here

或 - 用于保存到文件部分(最后两行):

NSString *path = @"./location.txt";
[NSKeyedArchiver archiveRootObject:array toFile:path];

1 个答案:

答案 0 :(得分:1)

// Get the path to the Documents (this is where your app saves data)
NSArray *searchPaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsPath = [searchPaths objectAtIndex: 0];
[array writeToFile:[documentsPath stringByAppendingPathComponent:@"location"] atomically:YES];

要将数据加载回数组,请使用

NSArray *searchPaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsPath = [searchPaths objectAtIndex: 0];
array = [[NSMutableArray alloc] initWithContentsOfFile:[documentsPath stringByAppendingPathComponent:@"location"];