tags:

views:

36

answers:

1

I'm having a problem in my application, CoreData works as it should in he simulator - but not on the device.

I receive an

2010-09-30 12:45:07.500 CoreDataTutorial_iOS[130:307] Unresolved error Error Domain=NSCocoaErrorDomain Code=513 "The operation couldn’t be completed. (Cocoa error 513.)" UserInfo=0x1412a0 {NSUnderlyingException=Error validating url for store}, {
    NSUnderlyingException = "Error validating url for store";

I'm calling for the PersistentStoreCoordinator in this function (which throws the error above):

-(NSPersistentStoreCoordinator*)persistentStoreCoordinator
{
    if(persistentStoreCoordinator_ != nil) 
        return persistentStoreCoordinator_;

    NSURL *aStoreURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingFormat:@"corebase.sqlite"]];
    NSError *anError = nil;

    persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if(![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:aStoreURL options:nil error:&anError])
    {
        NSLog(@"Unresolved error %@, %@", anError, [anError userInfo]);
        abort();
    }

    return persistentStoreCoordinator;
}

I'm setting a break point, on "objc_exception_throw", to see what the aStoreURL is, and it is: file://localhost/var/mobile/Applications/BE9A2982-BDC3-405D-A201-FB78E9E0790B/Documentscorebase.sqlite

I notice it's not itself adding the final "/" after "/Documents". When I created the URL this way

NSURL *aStoreURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingFormat:@"/corebase.sqlite"]];

It seems to have worked, or at least got passed that part. Shouldn't this function be appending that part itself?

-(NSString*) applicationDocumentsDirectory
{
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
}

It works fine in the simulator, what is the right practice?

A: 
NSURL *aStoreURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory]
                  stringByAppendingFormat: @"corebase.sqlite"]];

should be

NSURL *aStoreURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] 
           stringByAppendingPathComponent: @"corebase.sqlite"]];

stringByAppending*PathComponent* instead of stringByAppending*Format*. This nice little bug was brought to you by autocomplete :-)

Why it worked in the simulator? I guess because you are allowed to create files everywhere on the harddisk. So the Simulator created Documentscorebase.sqlite in your Apps Directory. You should check if it's there.

On the iphone you are limited to the Documents directory and are not allowed to create files everywhere.

fluchtpunkt