Until now, I've been using the following to initialize my NSPersistentStoreCoordinator's db path:
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true) lastObject];
However, Xcode now auto-populates my app delegate with a method
(NSURL *)applicationDocumentsDirectory:
which returns:
[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
Are there benefits or drawbacks to either one or are they just two ways of doing the exact same thing?
Using NSFileManager is the preferred way as written in the Docs: Foundation Functions Reference (NSSearchPathForDirectoriesInDomains)
You should consider using the NSFileManager methods URLsForDirectory:inDomains: and URLForDirectory:inDomain:appropriateForURL:create:error:. which return URLs, which are the preferred format.
I don't know if there are any real drawbacks when using NSSearchPathForDirectoriesInDomains to determine the URL to your documents directory. I would recommend to use NSFileManager and it's method as this is the quasi-convenient way.
Related
I am working on a app that is going to require the use of Core Data and I can't help but notice that Core Data has to be put in manually if you use anything but the Master-Detail, Utility or Blank templates in Xcode.
I also noticed that in order for Core Data to work properly, you HAVE to have your app wrapped in a Navigation Controller and Core Data's code in the AppDelegate files.
Anyone know of a way around this or is this the way it is supposed to be?
My App Delegate looks something like this and those three lines seem to be the most important setup for the ManagedObjectContext!
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
UINavigationController *navController = (UINavigationController *)self.window.rootViewController;
FBBetsViewController *controller = (FBBetsViewController *)navController.topViewController;
controller.managedObjectContext = self.managedObjectContext;
Those templates include some core data setup, but it is far from mandatory. You can use core data from within any project. If you want, you can just take the code from the empty application, and use it in your project.
If you look in the generated code, you will see three "getters" for the three main components used to build the core data stack.
managedObjectModel creates the model, by using the model file from your bundle. Create that easily in Xcode by New-File and selecting the Core Data Data Model.
persistentStoreCoordinator uses the model, and a SQL store.
Finally, managedObjectContext is created by using the persistentStoreCoordinator. Note, you really can build that stack in one method if you want. There is no requirement to have those individual accessors...
You could do something like this...
- (NSManagedObjectContext*)setupCoreDataStack
{
// Load the model description
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"APPNAME" withExtension:#"momd"];
NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
// Prepare the persistent store coordinator - needs the model
NSURL *documentsDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
NSURL *storeURL = [applicationDocumentsDirectory URLByAppendingPathComponent:#"APPNAME.sqlite"];
NSError *error = nil;
NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
if (![psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])
{
// Handle the error !!!!!
// exit the function
return nil;
}
// Create the managed object context. This is what you will really
// use in the rest of your program.
NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[moc setPersistentStoreCoordinator:psc];
return moc;
}
And now you have almost the same stack as the others. The only real difference is that the MOC here is using the main queue concurrency type, which is a much better alternative.
If you want to have a much better performance model, insert a parent moc.
Actually, if you are not married to a current cored data strategy, I'd suggest UIManagedDocument.
Core Data does not impose that you use a navigation controller nor that you set it up in the AppDelegate. It's customary to put the setup in the AppDelegate upon startup but really, you can move it wherever you want as long as you make sure it's only initialized once.
I started using CoreData in my application following Stanford CS193P lessons regarding the use of iOS 5's new class UIManagedDocument. The approach itself is quite straightforward but I can't understand how to deal with model modifications i keep making. This is how I instantiate my UIManagedDocument object (inside the appDelegate, so that every other class can use it):
if (!self.database) {
NSURL *url=[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
url = [url URLByAppendingPathComponent:#"AppName"];
UIManagedDocument *doc = [[UIManagedDocument alloc] initWithFileURL:url];
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
doc.persistentStoreOptions = options;
self.database=doc;
[doc release];
}
The issue I have is that every time I change even a little bit of my .xcdatamodel, I am unable to get all the content previously stored in the document as well as to create any new instance. As a matter of fact doing this generates the following exception:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'This NSPersistentStoreCoordinator has no persistent stores. It cannot perform a save operation.'
I thought setting the "options" property of the managed document would have solved the problem, but apparently this isn't enough.
Anyone can help? Couldn't' find other questions that actually fit my precise needs.
Before you modify your Core Data model, you should "Add Model Version".
1.
Select the original model file. (e.g. YourProject.xcdatamodel)
2.
"Editor" -> "Add Model Version...". Then add a new model version (e.g. 2.0)
3.
You will get a new model file. (e.g. YourProject 2.0.xcdatamodel). Modify it.
4.
Change the current model version. Select the top .xcdtatmodel file -> "View" -> "Utilities" -> "Show File Inspector". Find the tag "Versioned Core Data Model" and choose the right version you want to modify.
It also disturbed me for a long long time. Hope this way can help you ^^
There is a really simple solution to your problem. Simply erase the app from the simulator or device (touch the app icon for a few seconds, and touch the cross that appears when the app icons start wiggling). That way, Xcode updates your app's UIManagedDocument.
Make sure that you did not mistype NSDocumentDirectory as NSDocumentationDirectory.
NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
NSDocumentDirectory is right!
I am working on an iPhone app that uses a subclass of UIManagedDocument and stores its documents on iCloud.
It was all working fine until I changed my core data model / scheme (adding a new model version - like I had several times in the past few weeks).
I added a new property and changed the data type of one of the existing properties.
Now when I run my app I don't seem to be able to load my documents with UIManagedDocument's -openWithCompletionHandler:.
I can create new documents and read/write those.
If I change the data model version back 1 then I am able to read the existing docs, but not the new ones.
From what I understand I am only do lightweight migrations to the data model and UIManagedDocument is supposed to handle that right?
Any advice would be greatly appreciated!
Given below is based on my understanding:
NOTE - I haven't tried it for iCloud but I have tested it for non-icloud and seems ok.
UIManagedDocument configures the managedObjectModel and a Persistent Store Coordinator by itself
When migration needs to be done, just set the UIManagedDocument's persistentStoreOptions
//Note - In this example, managedDocument is a UIManagedDocument property
self.managedDocument.persistentStoreOptions = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
Refer:
Apple Documentation on Core Data Versioning
Point of using NSPersistentStoreCoordinator?
In a subclass of UIManagedDocument you may want to try overriding managedObjectModel like so:
- (NSManagedObjectModel *)managedObjectModel
{
NSString *path = [[NSBundle mainBundle] pathForResource:#"<ModelNameHere>" ofType:#"momd"];
NSURL *momURL = [NSURL fileURLWithPath:path];
NSManagedObjectModel *managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:momURL];
return managedObjectModel;
}
Dear community.
I try to discover opportunity to using 2 persistent stores for improve performance of my application.
What i do here:
CREATE 2 PERSISTENT STORES
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:[NSNumber numberWithBool:YES]
forKey:NSMigratePersistentStoresAutomaticallyOption];
if (![persistentStoreCoordinator addPersistentStoreWithType:NSInMemoryStoreType
configuration:nil
URL:[NSURL URLWithString:#"memory://store"]
options:dict
error:&error])
{
[[NSApplication sharedApplication] presentError:error];
[persistentStoreCoordinator release], persistentStoreCoordinator = nil;
return nil;
}
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:url
options:dict
error:&error])
{
[[NSApplication sharedApplication] presentError:error];
[persistentStoreCoordinator release], persistentStoreCoordinator = nil;
return nil;
}
ASSIGN new created objects to in-Memory store
NSManagedObject *objectCarrier = [NSEntityDescription
insertNewObjectForEntityForName:#"Carrier"
inManagedObjectContext:managedObjectContext];
[objectCarrier setValue:startForCarrier
forKey:#"name"];
NSURL *url = [NSURL URLWithString:#"memory://store"];
[managedObjectContext assignObject:objectCarrier
toPersistentStore:[[appDelegate persistentStoreCoordinator] persistentStoreForURL:url]];
SAVE FINAL OBJECT
A difference between in-memory and particular persistent store using is
i have wrong using objects from predicates for same code.
If i just change persistent store type, i pickup object:
NSManagedObject *destination = [[codeAfterComparing lastObject] valueForKey:codeRelationshipName];
But set values for this object is doesn't work.
If i try to assignObject for received object, i have error (it's doesnt matter, how this object was save as inMemory or asSqlLite store object, error is start every time).
2011-02-16 14:32:45.037 snow
server[44411:1803] * Terminating app
due to uncaught exception
'NSInvalidArgumentException', reason:
'Can't reassign an object to a
different store once it has been
saved.'
Attempt to save a final object's graph with two different stores gives me error "CoreData does not support persistent cross-store relationships", and it's doesn't matter, where cureent object assing.
Migration was as :
for (NSPersistentStore *persistentStore in [persistentStoreCoordinator persistentStores]) {
if (persistentStore.type == NSInMemoryStoreType) {
// migrate the in-memory store to a SQLite store
NSError *error;
[persistentStoreCoordinator migratePersistentStore:persistentStore toURL:[NSURL fileURLWithPath:[[self applicationSupportDirectory] stringByAppendingPathComponent:#"storedata.sql"]] options:nil withType:NSSQLiteStoreType error:&error];
if (! newPersistentStore) {
Product error: "Can't add the same store twice"
So, the result is a very strange for me:
1. Looks like managed object context have no difference for objects between 2 stores. If i ask save, it take whole object and save so same sqlite store
2. maybe a way to using different persistent store coordinator's but i don't know exactly, how is easy transfer objects between 2 stores. Of course, i can do a copy (include relationships e.t.c.) but this is a hard code for this simple issue, i guess.
Maybe somebody can suggest about my code wrong or good working examples of code to review and understand a good way to do in memory cache with core data? Google search gives not too much examples.
If you look at the Core Recipe example code on Apple's website, they use multiple stores to save objects in memory and on disk.
Thought I'd take a stab here.
I've had this problem in the past. I ended up removing the functionality for two persistent stores in the same coordinator. If I understand Apple correctly, Object Entities cannot be shared between persistent stores. So to make things easier, I usually just do the following (though I suspect there is an efficiency issue with using an additional Coordinator)
1 NSPersistentStore per NSPersistentStoreCoordinator
break up the scratchpad work to the NSManagedObjectContexts
create a deep-copy method to your NSManagedObject subclasses
And then, when whatever class you have managing each persistent store utilize the copy function to import the managed objects.
I can't really think of an instance where you'd want to go through the extra trouble of individually assigning the managed objects to a specific store that wouldn't be taken car of in this way.
I have a program that utilizes two stores - one in memory for transient objects and another managing the document. It's working just fine.
In iOS 5 Apple introduce Nested Managed Object Contexts where you can work with two Managed Object contexts.
This may replace your approach with the in memory store because e.g. you can now use one of the (also) new concurrency types to run one context in the background (e.g. for background fetching) and another as your main context.
Take a look in the WWDC2011 Session 303.
I tried to find the answer of my question on the internet, but I could not.
I have a simple entity in Core data that has a Value attribute (that is integer) and a Date attribute. I want to define two methods in my .m file.
First method is the ADD method. It takes two arguments: an integer value (entered by user in UI) and a date (current date by default). and then insert a record into the entity based on the arguments.
Second method is like an increment method. It uses the Date as a key to find a record and then increment the integer value of that record.
I don't know how to write these methods. (assume that we have an Array Controller for the table in the xib file)
The second method you are looking for is not appropriate to add to the entity itself. It needs to be somewhere above the entities, most likely in your controller object.
The first method is as follows:
- (void)updateDate:(NSDate*)date andValue:(NSInteger)value
{
[self setValue:date forKey:#"date"];
[self setValue:[NSNumber numberWithInteger:value] forKey:#"value"];
}
This is fairly straight KVC (Key-Value Coding) and I highly recommend that you read Apple's docs on the subject.
For your other method, that should be in a controller, you need to perform a fetch to find the record.
- (id)findRecordForDate:(NSDate*)date inManagedObjectContext:(NSManagedObjectContext*)moc
{
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:#"MyEntity" inManagedObjectContext:moc]];
[request setPredicate:[NSPredicate predicateWithFormat:#"date == %#", date]];
NSError *error = nil;
NSArray *objects = [moc executeFetchRequest:request error:&error];
NSAssert1(error == nil, #"Error fetching object: %#", [error localizedDescription]);
return [objects lastObject];
}
- (void)incrementEntityWithDate:(NSDate*)date
{
id entity = [self findRecordForDate:date inManagedObjectContext:[self managedObjectContext]];
NSInteger value = [[entity valueForKey:#"value"] integerValue];
value += 1;
[entity setValue:[NSNumber numberWithInteger:value] forKey:#"value"];
}
This is also very straightforward Core Data access. I recommend you read up on how Core Data works.
As an aside, using a date as a unique is a very bad design.
UPDATE
Marcus, Thanks for the answer. It is really helpful. I am new to core data so I have a few questions to make things clearer.
The code for the first method sets two values, but it doesn't insert the new record into the table. How can I insert the newly created record into the table?
You need to read up on how Core Data works. Apple has great documentation on how Core Data works and if that fails you can buy my book. There is a TON of information about how to use Core Data on the internet.
Where should I put the first method? in my .m file?
This is basic Objective-C. If you are asking this question you need to step way back and learn the fundamentals of the language first.
You mentioned that I need to add the second method in the controller. But the controller is defined in the xib file. How can I add the second method to that?
The controller is never defined in the xib file. It is referenced in the xib file. Again, you need to go back to the beginning of how Objective-C works and learn the basics before you dive this deep.