【问题标题】:write location / gps coordinates to a file将位置 / gps 坐标写入文件
【发布时间】:2011-06-29 17:07:44
【问题描述】:

好吧,我知道这听起来可能很简单,但我确实到处寻找,但找不到直接的答案。每次获得更新时,我都会尝试将位置坐标保存到文件中 - 听起来很简单....我有两个问题:一个是数据类型(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

OR - 保存到文件部分(最后两行):

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

【问题讨论】:

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


    【解决方案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"];
    

    【讨论】:

    • 谢谢,这很有帮助,但我怎样才能附加到文件末尾呢?我累了用它写了两次,然后当我阅读时,我只得到最后一次写。
    • @TommyG 当您在数组上使用 writeToFile 方法时,它将写出整个数组,覆盖之前的任何内容。因此,如果您正在创建一个新数组(而不是从文件中加载它),那么再次写出它只会写入自数组初始化以来添加到数组中的新数据。要追加,您需要将数据加载回数组中,然后将新数据添加到数组中,然后再次写出数组。根据您写入的数据量,您可能会遇到速度/内存问题。
    • 那么最好的做法是什么?当需要追加到文件末尾时人们会怎么做?
    • 这取决于数据量。如果您正在处理少量数据并且您需要重新使用以前的数据,只需使用它加载和保存即可。如果您正在查看大量数据,请考虑将核心数据用于数据库,然后在需要时将该数据写入文件。
    • 基本上我想保存用户位置,然后每天将其发送到服务器一次(例如)。所以每次我得到一个位置时,我都需要在本地保存它——这可能意味着每秒一次……所以我应该每秒加载和保存一次吗?我想要的只是保存一系列位置和时间戳。我必须将它附加到每个新样本,对吗?或者至少每次应用程序终止时(尽管它可以在后台运行),但仍然很可能会在一天内发生几次(意思是,直到我将它上传到服务器/数据库)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-19
    • 2012-11-15
    • 2016-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多