SQLite error code:14, 'unable to open database file' - macos

In my cocoa application, i am using core data to maintain all my datas. But some time ,i am getting the below given issue.
Issue:
CoreData: error: (14) I/O error for database at /Users/my-mac/Documents/FileT.sqlite. SQLite error code:14, 'unable to open database file'
Here i given the code reference for persistentStoreCoordinator :
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory]
stringByAppendingPathComponent: #"FileT.sqlite"]];
NSError *error = nil;
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]
initWithManagedObjectModel:[self managedObjectModel]];
options = #{
NSMigratePersistentStoresAutomaticallyOption : #YES,
NSInferMappingModelAutomaticallyOption : #YES
};
if(![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil URL:storeUrl options:options error:&error]) {
/*Error for store creation should be handled in here*/
}
return _persistentStoreCoordinator;
}
Can anyone suggest what i am missing here?

Take a look at Technical Q&A 1809: New default journaling mode for Core Data SQLite stores in iOS 7 and OS X Mavericks
Your application may be moving or changing the WAL journal files or SQLite files, or may have made assumptions about the file structure that was valid for versions of Core Data that did not use WAL.
It's also possible that your SQLite database is being corrupted, and the error 14 is SQLite attempting to repair the file when Core Data opens it. This corruption can happen if the application was not shut down properly when a write was happening - and many other circumstances. Not shutting down properly is the most common case on Apple platforms though - for example, if Core Data is writing records and the OS kills the application because it's unresponsive. That can cause corruption.

Related

dictionaryWithContentsOfFile and Sandbox

I've created a mac app that load a xml file from an user selected folder, and after using the app, the user saves a customized file (.adgf)
When i try to load the .adgf file (that is a plist file) that has the xml path within one record i call
dictionaryWithContentsOfFile but it return me a "nil". I think the problem is the sandbox (sometime it works sometime not). The string path is correct.
Maybe when the user load the xml file should i save within of particular app "Document folder"?
Edit:
I'm trying right now the Bookmark Data solution and I retraive a NSURL but it doen't work. The code I'm using is this:
- (NSData *)bookmarkFromURL:(NSURL *)url {
NSError *error = nil;
NSData *bookmark = [url bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope
includingResourceValuesForKeys:NULL
relativeToURL:NULL
error:&error];
if (error) {
NSLog(#"Error creating bookmark for URL (%#): %#", url, error);
[NSApp presentError:error];
}
return bookmark;
}
- (NSURL *)urlFromBookmark:(NSData *)bookmark {
NSURL *url = [NSURL URLByResolvingBookmarkData:bookmark
options:NSURLBookmarkResolutionWithSecurityScope
relativeToURL:NULL
bookmarkDataIsStale:NO
error:NULL];
return url;
}
After the user stores the file you should take the bookmark data from the URL using
-[NSURL bookmarkDataWithOptions: includingResourceValuesForKeys: relativeToURL: error:]
Use NSURLBookmarkCreationWithSecurityScope for the options.
This NSData object should be stored somewhere (plist?) and when you want to read the file again in a later session you can create a sandbox compliant NSURL from the bookmark data using +[NSURL
URLByResolvingBookmarkData:options:relativeToURL:bookmarkDataIsStale:error:]

RestKit 2.0 Removing RKManagedObjectStore but keeping NSManagedObjectModel

I have a project set up where all data coming from the Server is wrote to a Core Data managed store using a managed model. I have all my entities generated from the Core Data model using mogenerator. I have all RestKit mapping integrated in to my entities.
NSError *error = nil;
NSURL *modelURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"dataModel" ofType:#"momd"]];
// NOTE: Due to an iOS 5 bug, the managed object model returned is immutable.
NSManagedObjectModel *managedObjectModel = [[[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL] mutableCopy];
RKManagedObjectStore *managedObjectStore = [[RKManagedObjectStore alloc] initWithManagedObjectModel:managedObjectModel];
// Initialize the Core Data stack
[managedObjectStore createPersistentStoreCoordinator];
NSPersistentStore __unused *persistentStore = [managedObjectStore addInMemoryPersistentStore:&error];
NSAssert(persistentStore, #"Failed to add persistent store: %#", error);
[managedObjectStore createManagedObjectContexts];
// Set the default store shared instance
[RKManagedObjectStore setDefaultStore:managedObjectStore];
Now there has been a change of plan due to time constraints. The data should not be stored at all. The data should be read from the server and displayed directly. No saving, no persisting. So I would like to cut out the RKManagedObjectStore, keep the entities and mappings, and read the data from 'RKMappingResult *mappingResult' when a request succeeds or a RKPaginator resutl. Example that works with RKManagedObjectStore and RKPaginator:
[objectManager addResponseDescriptor:[RKResponseDescriptor responseDescriptorWithMapping:[Friend entityMapping:objectManager.managedObjectStore]
method:RKRequestMethodAny
pathPattern:nil
keyPath:#"items"
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)]];
[objectManager setPaginationMapping:[self paginationMapping]];
self.paginator = [objectManager paginatorWithPathPattern:#"data"];
self.paginator.perPage = 20;
//Set completion block for this paginator
[self.paginator setCompletionBlockWithSuccess:^(RKPaginator *paginator, NSArray *objects, NSUInteger page) {
[weakSelf.dataArray addObjectsFromArray:objects];
} failure:^(RKPaginator *paginator, NSError *error) {
}];
However, when I start to reomve the RKManagedObjectStore I start to run into problems when mapping.
'You must provide a managedObjectStore. Invoke mappingForClass:inManagedObjectStore: instead.'
Q.1 Can I use Enitiy Mapping without RKManagedObjectStore? Am I going in the right direction.
Q.2 Can I remove the store and keep the model?
Any tips, help or examples would be great before I get too involved and go in the wrong direction.
Thanks Al
You should fight against the requirement change and use Core Data as a temporary cache of information to aid with memory management (so you can scroll up and down lists without having to have everything loaded all the time). This should not take any longer to implement...
No, you can't use RKEntityMapping without an RKManagedObjectStore.
You could keep the model but you wouldn't be able to use it (managed objects need to be created in association with a MOC).

RestKit › [RestKit 0.9] Swap core data database at runtime

Le mardi 18 juin 2013 12:50:29 UTC+2, Appsido a écrit :
Hello,
I'm facing an issue trying to create a new persistent store at runtime and use this new persistent store.
To create the new persistent store i use the following snippet
NSURL *modelUrl = [[NSBundle bundleForClass:[self class]] URLForResource:#"AppDataModel" withExtension:#"momd"];
NSManagedObjectModel *managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelUrl];
[[AppDelegate appDelegate] objectManager].objectStore = [RKManagedObjectStore objectStoreWithStoreFilename:#"AppStore"
usingSeedDatabaseName:nil
managedObjectModel: managedObjectModel
delegate:nil];
This works fine and create a new persistent store on the iphone device file system.
Then i create a new object and save it in the persistent store with the following snippet
MyEntity *f = [MyEntity object];
[f setValue:[NSNumber numberWithInt:70] forKey:#"id"];
[f setValue:#"New Family" forKey:#"name"];
NSError *error;
[[f managedObjectContext] save:&error];
if (error) NSLog(#"error > %#", error);
The object is saved in persistent store but not the new created one but the old one.
So is it possible to define multiple persistent store based on the same data model file and swap from one to another at runtime, and keep data in each persistent store instance.
Thank you for your support.
Look at https://github.com/magicalpanda/MagicalRecord
// get the default context
[NSManagedObjectContext MR_defaultContext];
// create the other context
NSManagedObjectContext *myNewContext = [NSManagedObjectContext MR_context];
// set the new default
[NSManagedObjectContext MR_setDefaultContext:myNewContext];
You will need somewhere to strore the contexts to keep swapping between them, maybe a dictionary.
You should at first delete old one persistentStore with this code
[objectManager.objectStore deletePersistantStore];

Storing UIManagedDocuments when uibiquity container (iCloud) is not available

I've managed to understand how to incorporate UIManagedDocument into a simple test application and it works as expected! However, now I'm adding support to this basic application so it will work if the user does not want to use iCloud.
So when the URLForUbiquityContainerIdentifier: method returns 'nil', I return the URL of the local documents directory using the suggested method
NSString *documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
return [NSURL fileURLWithPath:documentsDirectoryPath];
However, when I try saving a UIManagedDocument to the local URL (such as: file://localhost/var/mobile/Applications/some-long-identifier/Documents/d.dox) I get the following error:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'This NSPersistentStoreCoordinator has no persistent stores. It cannot perform a save operation.'
Using this save method:
if (![[NSFileManager defaultManager] fileExistsAtPath:self.managedDocument.fileURL.path]) {
[self.documentDatabase saveToURL:self.managedDocument.fileURL
forSaveOperation:UIDocumentSaveForCreating
completionHandler:^(BOOL success) {
if (success) {
//
// Add default database stuff here.
//
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self.documentDatabase.managedObjectContext performBlock:^{
[Note newNoteInContext:self.managedDocument.managedObjectContext];
}];
});
} else {
NSLog(#"Error saving %#", self.managedDocument.fileURL.lastPathComponent);
}
}];
}
It turns out my persistent store options contained the keys used for the ubiquitous store. These shouldn't be in the documents persistent store options.

What is the encoding for URL bookmarks stored as NSData?

What is the best way to get the path from the NSData bookmark object, if the bookmark will not resolve?
Normally, you just resolve the bookmark, you get a URL, and off you go. But if the bookmark is to an NFS mount that is not currently present, it won't resolve. So now I have an NSData pointing somewhere that won't resolve, but I don't know where it points.
Here is the code block I have that loads the bookmarks, tries to resolve them, and attempts to decode the NSData if the resolve fails, but I can't figure out the encoding - is this even possible?
NSError* error = [[NSError alloc] init];
NSURL* resolvedURL = [NSURL URLByResolvingBookmarkData:bookmarkData
options:NSURLBookmarkResolutionWithSecurityScope | NSURLBookmarkResolutionWithoutUI
relativeToURL:nil
bookmarkDataIsStale:NULL
error:&error];
if (resolvedURL) {
// do some stuff
...
} else {
NSString* msg = [NSString stringWithFormat:#"Error Resolving Bookmark: %#", error];
NSLog(msg);
// the below certainly doesn't get me a path from the bookmark, any idea what will?
// NSString* path = [[NSString alloc] initWithData:bookmarkData encoding:NSUTF32StringEncoding];
}
I never did figure out the encoding, but I found a workaround.
Originally, I encoded the sandboxed NSURLs into NSData objects, and then stored those as an NSArray in NSDefaults. Therefore, I had no way to determine the path for the NSData, unless it would resolve.
The workaround was to change the design - now I encode the sandboxed NSURL, store it as an object into an NSDictionary with the key being the URL path, and store the NSDictionary in NSDefaults.
With this approach, I can easily retrieve the NSData for any given path, even if it will not resolve.

Resources