I'm stuck trying to add Core Data to my existing iOS project. I don't have an existing sql database but I created a data model. I followed the following tutorial: http://wiresareobsolete.com/wordpress/2009/12/adding-core-data-existing-iphone-projects/
It produces an error at the following code:
(NSPersistentStoreCoordinator *) persistentStoreCoordinator{
if (persistentStoreCoordinator != nil){
return persistentStoreCoordinator;
}
NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentDirectory]
stringByAppendingPathComponent: @"MyPOC.sqlite"]];
NSError *error = nil;
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]
initWithManagedObjectModel:[self managedObjectModel]];
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]){
NSLog(@"Unresolved error OH NO %@, %@", error, [error userInfo]);
}
return persistentStoreCoordinator;
}
I get the following error:
2012-10-25 13:52:29.156 MyPOC[1994:11603] Unresolved error OH NO Error
Domain=NSCocoaErrorDomain Code=512 "The operation couldn’t be completed.
(Cocoa error 512.)" UserInfo=0x8246240 {reason=Failed to create file; code = 2},
{reason = "Failed to create file; code = 2";}
I really have no idea why it crashes and how I can resolve it. If more information is needed to help please let me know.
I was following nearly the same tutorial and receiving the same error message. I figured out what the problem is though.
In my case, the file could not be created because the storeURL path was incorrect and pointing to a folder that didn't exist.
In my helper method [self applicationDocumentDirectory] (which you did not provide in your question) I typed in the sample code just like in the tutorial:
- (NSString *) applicationDocumentsDirectory
{
return [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES) lastObject];
}
which produced the URL file:///Users/xxxxxx/Library/Application%20Support/iPhone%20Simulator/7.0.3/Applications/A6FDD8DB-475B-4C9B-B995-28CCE068DF82/
Library/Documentation/
There is a silly code completion typo in there which generates an invalid path. Can you see it?
It's the enum NSDocumentationDirectory for the NSSearchPathDirectory input parameter, it should be NSDocumentDirectory instead.
The correct code and URL is:
- (NSString *) applicationDocumentsDirectory
{
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject;
}
URL: file:///Users/xxxxxx/Library/Application%20Support/iPhone%20Simulator/7.0.3/Applications/A6FDD8DB-475B-4C9B-B995-28CCE068DF82/
Documents/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With