【问题标题】:How to store a CLLocation object using NSKeyedArchiver?如何使用 NSKeyedArchiver 存储 CLLocation 对象?
【发布时间】:2014-02-08 16:04:40
【问题描述】:

我有点困惑为什么以下不起作用。有人能启发我吗?

我有一个返回filePath的函数:

- (NSString *) lastLocationPersistenceFilePath {
    NSString *filePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingString:@"last_location"];
    return filePath;
}

然后,在按钮触发的方法中,我尝试像这样保存CLLocation 对象:

// Store this location so it can persist:
BOOL success = [NSKeyedArchiver archiveRootObject:_startLocation toFile:[self lastLocationPersistenceFilePath]];
if (!success) {
    NSLog(@"Could not persist location for some reason!");
} else {
    NSLog(@"New location has been stored.");
}

在我的viewDidLoad: 中,我尝试加载它:

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Retrieve last location:
    CLLocation *decodedLocation = [NSKeyedUnarchiver unarchiveObjectWithFile:[self lastLocationPersistenceFilePath]];

    if (decodedLocation) {
        _startLocation = decodedLocation;
    } else {
        NSLog(@"Decoding failed.");
    }
}

存档失败,当然,这意味着我也无法解码任何内容。我觉得我遗漏了一些明显/琐碎的东西……有什么建议吗?

【问题讨论】:

    标签: ios cllocation nskeyedarchiver


    【解决方案1】:

    简单地说,无法写入应用程序的资源目录。而是写入应用的文档目录。

    代码示例”

    - (NSString *) lastLocationPersistenceFilePath {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentDirectory = [paths firstObject];
        NSString *filePath = [documentDirectory stringByAppendingPathComponent:@"last_location"];
        return filePath;
    }
    

    【讨论】:

    • 非常感谢您的回复。我已经用你的方法代替了我的方法,但它仍然没有存储对象。我希望我能提供更多有用的信息,而不是仅仅说“它不起作用”。还有什么我可以尝试或检查的吗?
    • 我可以通过关注this solution 让它工作。也就是说,我使用NSUserDefaults 将纬度和经度存储为双精度值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-17
    • 1970-01-01
    相关资源
    最近更新 更多