2014-02-08 48 views
0

我有点困惑,为什么以下不起作用。有人能够启发我吗?如何使用NSKeyedArchiver存储CLLocation对象?

我有一个返回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."); 
    } 
} 

归档fa当然,这意味着我无法解码任何东西。我觉得我错过了某些明显/琐碎的事情......任何指针?

回答

3

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

代码示例”

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

非常感谢您的回复,我已经取代我的方法与你的,但它仍然没有存储的对象。我希望我能提供更多有用的信息,而不是仅仅说'它不工作'。还有什么我可以尝试或检查吗? – Florian

+0

我可以通过下面的[这个解决方案]得到它的工作(http://stackoverflow.com/questions/1813166/persisting-corelocation)。 ,我使用'NSUserDefaults'将经度和纬度存储为双精度。 – Florian