How to completely clear out a Core Data model? - iphone

How I could completely clear out EVERYTHING in a Core Data model i.e remove all objects for all entities?
I will be using the code to clear out the saved history in a the model.

Here is another way to do...
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSFetchRequest * allMovies = [[NSFetchRequest alloc] init];
[allMovies setEntity:[NSEntityDescription entityForName:#"Movies" inManagedObjectContext:context]];
[allMovies setIncludesPropertyValues:NO]; //only fetch the managedObjectID
NSError * error = nil;
NSArray * movies = [context executeFetchRequest:allMovies error:&error];
//error handling goes here
for (NSManagedObject * movie in movies) {
[context deleteObject:movie];
}
NSError *saveError = nil;
[context save:&saveError];
It will clear all the objects.

Delete the .sqlite DB Core Data creates (it's probably stored on your /Documents directory) and get your app to re-create it.

Here is a good answer to this question.
Delete/Reset all entries in Core Data?
Then just make sure to re-create the store.

Related

Xcode loading core data lag

I have 3 entities saved in core data. I am loading these in several view controllers in the app - sometimes loading data from all 3. Below is how I am loading this data and assign it to an array. Once it is in the array, then I sort, filter, count or whatever I need to do depending on the current page of the app.
if (managedObjectContext == nil)
{
managedObjectContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
}
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Event" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
[request setReturnsObjectsAsFaults:NO];
NSError *error = nil;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil)
{
// Handle the error.
NSLog(#"mutableFetchResults == nil");
}
[self setEventsArray:mutableFetchResults];
The problems I am having are:
I don't like to have lots of duplicate code - and this is appearing on every view controller where core data is needed.
From one entity, I am saving binary data of images which is causing a lag when I load that data
So, is there a way to load from core data using conditions such as eventId = [NSString stringWithFormat:#"%#", currentEventId]
OR (and probably more suitable) have a separate class that loads the data when the app starts. And then I can access the classes arrays (of the loaded data) to use for the current page. And then just reload the data if I save, edit or delete an object.
Any help is much appreciated.
Fro your first question, you should look at MagicalRecord which brings Ruby on Rails' Active Record to CoreData. it will shorten clear your core data code.
Pay attention that if your images are not small you should store them on a separate entity with a relationship to your main entity. this should help you with the lag problem since you will load the image trough the relationship only when you will explicitly ask it to. You can see here the answer of Marcus Zarra (wrote a great book on core data). There is always an option that your images are too big for core data.
Hope it helps

Core Data. ExecuteFetchRequest with fault NSManagedObjects (not in RAM)

I need to execute fetch request. But when I do it I get not fault NSManagedObjects (each of the objects is about 5 Mb, that's why I get the memory warning). Apple provides faulting possibility for Core Data (when objects are not loaded in RAM). And I wanna my objects to use this possibility.
Here is my code
+ (NSMutableSet *)GetImagesWithPredicate:(NSPredicate *)predicate
{
NSString *entityName = kEntityName;
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];;
NSManagedObjectContext *context = appDelegate.managedObjectContext;
NSEntityDescription *entityDesctiption = [NSEntityDescription
entityForName: entityName
inManagedObjectContext:context];
// find object
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesctiption];
[request setPredicate:predicate];
NSArray *objects = [context executeFetchRequest:request error:nil];
[request release];
if (objects == nil)
{
NSLog(#"there was an error");
return nil;
}
NSMutableSet *set = [NSMutableSet setWithArray:objects];
return set;
}
where predicate is (id < 500).
App crashes after
NSArray *objects = [context executeFetchRequest:request error:nil];
because all the data of objects appears in the RAM of iPhone.
It seems that default option returnsObjectsAsFaults = YES doesn't work.
The objects are probably being returned as faults; you can verify this with isFault. The issue is that Core Data automatically pre-fetches the property values for those objects and places them in the row cache (in memory). You can disable this behaviour by setting includesPropertyValues to NO on the NSFetchRequest object.
See the includesPropertyValues documentation for details of all this and the performance implications.
As an aside, you might not want to store lots of large objects in the database directly. You probably should look into using external storage if you're targeting iOS 5, or else using separate files yourself with their names/paths/ids in Core Data.
you could set the - (void)setResultType:(NSFetchRequestResultType)type for the NSFetchRequest and only get the relevant attributes for your Object with the -(void)setPropertiesToFetch:(NSArray *)values Method.
And only lazy loading the needed attributes.

Populating the Tableview from the Core Data

I have performed the save operation in core data and it is successfully done .It stores the data .I have also fetched the data into the log. This is my code for fetching data in log but I dont know how to fetch this data in TableView.
NSError *error;
DemoAppCoreDataAppDelegate *appdelegate = (DemoAppCoreDataAppDelegate *)[[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = [appdelegate managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName: #"Employee" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedobject = [context executeFetchRequest:fetchRequest error:&error];
tablearray = [[NSMutableArray alloc] initWithArray:fetchedobject copyItems:YES];
for (NSManagedObject *info in fetchedobject ) {
NSLog(# "%#",[info valueForKey:#"name"] );
}
[fetchRequest release];
I would recommend to use a NSFetchedResultsController.
Apple provides complete sample code in the NSFetchedResultsController documentation
The NSFetchedResultsController is specifically designed to work in between a tableView and Core Data. It makes everything a lot easier.
For example it will automatically insert and delete rows when you add or remove objects from the core data. For this you have to implement the NSFetchedResultsControllerDelegate protocol. The full sample code for this is in the protocol documentation
Use fetchedobject as dataSource to the tableView.
After [fetchRequest release]; , set the delegate and datasource for the tableView programatically.
The best way in this case is to inspect some working example I think. Look at the apple's example project Recipies, good one btw: easy and gives a good picture of how the things with CoreData and tableViews should be done:
http://developer.apple.com/library/ios/#samplecode/iPhoneCoreDataRecipes/Introduction/Intro.html#//apple_ref/doc/uid/DTS40008913

iPhone - App crashes when trying to save new objects after deleting objects in CoreData

Okay, I'm having a problem saving after I've deleted all the objects I have stored in CoreData. I have no problem with saving if I don't delete anything, but as soon as I ask it to delete all the objects (everything deletes with no errors or problems), and then try saving again, it crashes and just gives me a program received signal: SIGABRT. Here's my code.
- (void)deleteStoredData
{
// Define our table/entity to use
NSEntityDescription *entity = [NSEntityDescription entityForName:MOVIE_LIST inManagedObjectContext:managedObjectContext];
// Setup the fetch request
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
// Fetch the records and handle an error
NSError *error;
NSUInteger count = [managedObjectContext countForFetchRequest:request error:&error];
if (count) {
for (int i = 0; i < count - 1; i++) {
NSManagedObject *eventToDelete = [self.listOfMovies objectAtIndex:i];
[managedObjectContext deleteObject:eventToDelete];
}
}
[request release];
}
I thought it might be me comparing self.listOfMovies to the objects stored, so I did a fresh fetch, copied it to a temp NSMutableArray, then replaced self.listOfMovies with temp. But no changes, still crashes. Did I some how delete the entire record and it no longer exists?
What I want to do is load everything onto the app, then delete all the objects in CoreData, so that when the app closes (or terminates) it saves all the new data in the records. Am I doing this correctly, or is there a much easier way to do this? Oh yea, and I only have one entity that holds 5 NSStrings, so nothing to complicated.
Thanks in advance everyone.
Possibly, when you call the save method, there might be some mixup with some variable such as the managedObjectContext.
Did you try saving right after the deletion (i.e. in your deleteStoredData method above)?
BTW, I would also go with Christopher's code;-).
Deleting managed objects with a for loop like that is error prone and probably corrupting your managedObjectContext. Try the following:
NSFetchRequest * fetch = [[[NSFetchRequest alloc] init] autorelease];
[fetch setEntity:[NSEntityDescription entityForName:MOVIE_LIST inManagedObjectContext:context]];
NSArray * result = [context executeFetchRequest:fetch error:nil];
for (NSManagedObject * event in result) {
[context deleteObject:event];
}
Since you are already have all of managedObject in your array, you do NOT need to do another fetch, just delete them with the code below should be OK.
for (NSUInteger i = 0; i < [self.listOfMovies count] - 1; i++) {
NSManagedObject *eventToDelete = [self.listOfMovies objectAtIndex:i];
[managedObjectContext deleteObject:eventToDelete];
}
If it still have problem, would you please tell me how many managedObjectContext do you have in your App? Are you deleting or saving it in a background thread?
In addition, would you please also post the crash log and the information by type "bt -> enter key" in console after your App crashed?

Query interface for iPhone CoreData store

another iPhone newbie question...
I have the following:
NSPersistentStoreCoordinator
NSManagedObjectContext
NSManagedObjectModel
Is it possible to run queries directly on the store (since its a sqlite DB)? I'm trying to delete all the records from a tableview, and figured a "DELETE FROM table" would be nice and quick as opposed to looping through the records and removing them manually (which i'm also struggling with).
Thanks for your time,
James
Core data acts as a wrapper for the underlying data store, so it's not really a great idea to begin circumventing core data. Additionally, core data adds additional information to your DB, so directly accessing the DB may (or may in the future) cause problems.
To delete all records via core data, I have the following:
+ (void) deleteAll {
NSManagedObjectContext *managedObjectContext = [(myAppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:[[self class] description] inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
NSError *error;
NSArray *items = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
[fetchRequest release];
for (NSManagedObject *managedObject in items) {
[managedObjectContext deleteObject:managedObject];
NSLog(#"%# object deleted",[[self class] description]);
}
}