0

I am slightly confused why the following doesn't work. Can someone enlighten me?

I have one function that returns a filePath:

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

Then, in a method triggered by a button, I attempt to save a CLLocation object like so:

// 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.");
}

In my viewDidLoad:, I attempt to load it:

- (void)viewDidLoad
{
    [super viewDidLoad];

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

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

The archiving fails which, of course, means I can't decode anything either. I feel like I am missing something obvious/trivial... any pointers?

Florian
  • 579
  • 1
  • 10
  • 19

1 Answers1

3

Simply, it is not possible to write to the the app's resource directory. Instead write to the app's document directory.

Code example"

- (NSString *) lastLocationPersistenceFilePath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [paths firstObject];
    NSString *filePath = [documentDirectory stringByAppendingPathComponent:@"last_location"];
    return filePath;
}
zaph
  • 111,848
  • 21
  • 189
  • 228
  • Thanks a lot for your reply. I have substituted my method with yours but it still doesn't store the object. I wish I could provide more helpful info instead of just saying 'it doesn't work'. Anything else I could try or check? – Florian Feb 08 '14 at 20:30
  • I was able to get it to work by following [this solution](http://stackoverflow.com/questions/1813166/persisting-corelocation). That is, I stored the latitude and longitude as doubles using `NSUserDefaults`. – Florian Feb 08 '14 at 23:01