Strange behavior in deleting core data contents - ios

I use the following code to delete the coredata DB contents... I get the notification properly..But it seems the data are not deleted... I can't figure it out...
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:entityDescription inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSError *errors;
NSArray *items = [self.managedObjectContext executeFetchRequest:fetchRequest error:&errors];
NSLog(#"FinalArray:%#",[finalArray objectAtIndex:currentImageIndex]);
NSManagedObject *managedObject=[finalArray objectAtIndex:currentImageIndex];
NSLog(#"NSManagedObject:%#",managedObject);
for (int i=0;i<[items count];i++)
{
if ([managedObject isEqual:[items objectAtIndex:i]])
{
[self.managedObjectContext deleteObject:managedObject];
NSLog(#"gone");
}
}
NSNotificationCenter *nc=[NSNotificationCenter defaultCenter];
[nc addObserver:self selector:#selector(deleteCheck:) name:NSManagedObjectContextObjectsDidChangeNotification object:self.managedObjectContext];
NSLog(#"dffsdf%#",[errors description]);
if (self.managedObjectContext==nil)
{
NSLog(#"deleted");
}
Notification Func call
- (void)deleteCheck:(NSNotification *)notification
{
NSLog(#"CoreData got Deleted");
NSDictionary *userInfoDictionary = [notification userInfo];
NSSet *deletedObjects = [userInfoDictionary objectForKey:NSDeletedObjectsKey];
NSLog(#"DeletedObjects%#",deletedObjects);
}
Since NSManagedObjectContextObjectsDidChangeNotification notification called for each time when I tap the delete button... But no effects in DB... Suggestions Please

You need to save at the end.
NSError *error = nil;
[self.managedObjectContext save:&error];

You can use this simple delete method that i use, its work perfect :
-(void)deleteRecords{
NSFetchRequest * deleteRequest = [[[NSFetchRequest alloc] init] autorelease];
[deleteRequest setEntity:[NSEntityDescription entityForName:#"yourTabelName" inManagedObjectContext:context]];
[deleteRequest setIncludesPropertyValues:NO]; //only fetch the managedObjectID
NSError * error = nil;
NSArray * cars = [context executeFetchRequest:deleteRequest error:&error];
if ([cars count] !=0) {
//error handling goes here
for (NSManagedObject * car in cars) {
[context deleteObject:car];
}
NSError *saveError = nil;
[context save:&saveError];
// [tableView reloadData];
}
else {
NSLog(#"No Data To delete");
} }

Related

Update NSManagedObjectContext

Please consider the method at the end of this question. It attempts to delete all records from a CoreData entity.
The first -outcommented- part works fine: it deletes everything from my context, and then saves the context.
The second, non-commented part doesn't seem to work:
As a test I do
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:#"myEntity"];
NSError *error = nil;
NSArray *results = [self.managedObjectContext executeFetchRequest:request error:&error];
NSLog(#"Fetch request returns %lu objects", (unsigned long)[results count]);
When I add records, and delete all records with the method below, the amount of records only increase.
As far as I understand, it actually works, but the context is not aware of it (yet).
So, therefore, in order to get a reliable context, I should update the context with
[NSManagedObjectContext mergeChangesFromRemoteContextSave:<#(nonnull NSDictionary *)#> intoContexts:self.managedObjectContext];
However, I don't have a clue what I should enter in the (nonnull NSDictionary *) part.
BTW: I only want to use the NSBatchDeleteRequest because I assume it is faster than iterating through all records.
- (void)deleteAllEntities:(NSString *)nameEntity
{
id appDelegate = (id)[[UIApplication sharedApplication] delegate];
self.managedObjectContext= [appDelegate managedObjectContext];
/*
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:nameEntity];
[fetchRequest setIncludesPropertyValues:NO]; //only fetch the managedObjectID
NSError *error;
NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *object in fetchedObjects)
{
[self.managedObjectContext deleteObject:object];
}
error = nil;
[self.managedObjectContext save:&error];
*/
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:nameEntity];
NSBatchDeleteRequest *delete = [[NSBatchDeleteRequest alloc] initWithFetchRequest:request];
NSError *deleteError = nil;
}

How to delete entries in core data

i am new to core data..
I know how to store and item.
- (void)dbSave:(NSString *)uri withContent:(NSDictionary *)content withExpiry:(double)date {
Cache *cache = [self dbLoad:uri];
if (cache == nil) {
cache = [NSEntityDescription insertNewObjectForEntityForName:#"Cache" inManagedObjectContext:[self managedObjectContext]];
}
double time = (double) [[NSDate date] timeIntervalSince1970] + date;
[cache setLocal:uri];
[cache setTime:#(time)];
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:content forKey:#"data"];
[archiver finishEncoding];
[cache setData:data];
NSError *error;
if (![[self managedObjectContext] save:&error]) {
}
}
But i am stuck with creating a method to clear this core data data base.. Does anyone know how?
NSManagedObjectContext *managedObjectContext=[appDelegate managedObjectContext];
NSFetchRequest *fetchRequest=[NSFetchRequest fetchRequestWithEntityName:#"entity"];
NSArray* currentRecord = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
if (currentRecord.count)
{
for (NSManagedObject *obj in currentRecord)
{
[managedObjectContext deleteObject:obj];
}
NSError * error = nil;
if (![managedObjectContext save:&error])
NSLog(#"Can't save ! %# %#",error,[error localizedDescription]);
else
NSLog(#"Data deleted");
}
use this
NSManagedObjectContext *managedContext = [[APP_DELEGATE dbManagerObj] newPrivateContext];
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:#"Cache"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"isUserData = %#",[NSNumber numberWithBool:true]];
[fetchRequest setPredicate:predicate];
if (IS_IOS9_ANDABOVE) {
NSBatchDeleteRequest *batchDeleteRequest = [[NSBatchDeleteRequest alloc]initWithFetchRequest:fetchRequest];
[[[APP_DELEGATE dbManagerObj]persistentStoreCoordinator]executeRequest:batchDeleteRequest withContext:managedContext error:nil];
}
else
{
NSArray *userRelatedDay = [managedContext executeFetchRequest:fetchRequest error:nil];
for (NSManagedObject *object in userRelatedDay) {
[managedContext deleteObject:object];
}
}

malloc: *** error for object 0x14d3e300: double free CoreData

I have this function to fetch data to CoreData.
This information is used to update a UITableView.
- (NSArray*)haveNewContentsInCategory{
NSArray *aux = [self fetchAllReceiptCategorys];
NSMutableArray *hiddens=[[NSMutableArray alloc] init];
for (ReceiptCategory *rec in aux) {
NSEntityDescription *entDesc = [NSEntityDescription entityForName:#"Content" inManagedObjectContext:self.managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entDesc];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"categoryId == %#",rec.catId];
[request setPredicate:predicate];
NSError *error;
NSArray *results = [self.managedObjectContext executeFetchRequest:request error:&error];
BOOL hidden=NO;
for (Content *cont in results) {
if ([cont.newContent boolValue]) {
hidden=YES;
}
}
[hiddens addObject:[[NSNumber alloc] initWithBool:hidden]];
}
return hiddens;
}
View Controller
- (void)viewWillAppear:(BOOL)animated{
categorys = [[CoreDataManager instance] fetchAllReceiptCategorys];
hiddens = [[CoreDataManager instance] haveNewContentsInCategory];
[_tvTable reloadData];
}
The first time you press the view everything works fine. but when I go to this view a second time this error happens.
malloc: * error for object 0x14d3e300: double free
* set a breakpoint in malloc_error_break to debug

executeFetchRequest taking too long .

Even though I don't have more than 3 records in my table , and a single table. Method : executeFetchRequest takes too long
loanIDArray=[[NSMutableArray alloc]init];
appDelegate=[[UIApplication sharedApplication] delegate];
context=[appDelegate managedObjectContext];
entityDesc=[NSEntityDescription entityForName:#"Personal_Info" inManagedObjectContext:context];
NSFetchRequest* request=[[NSFetchRequest alloc]init];
[request setEntity:entityDesc];
NSPredicate* predicate=[NSPredicate predicateWithFormat:#"status_of_form==%#",#"Completed"];
[request setPredicate:predicate];
NSError* fetchError;
NSError* error;
This line takes too long
NSArray* objects = [context executeFetchRequest:request error:&fetchError];
if (!fetchError) {
for (NSManagedObject* obj in objects) {
[loanIDArray addObject:[obj valueForKey:#"app_id"]];
}
}
else
NSLog(#"Status Fetch Error : %#",fetchError.description);
[context save:&error];
if (!error)
NSLog(#"count : %d",loanIDArray.count );
else
NSLog(#"error : %#",error.description);
try replace this code:
if (!fetchError) {
for (NSManagedObject* obj in objects) {
[loanIDArray addObject:[obj valueForKey:#"app_id"]];
}
}
with this to avoid iteration:
if (!fetchError) {
loanIDArray = [objects valueForKeyPath:#"app_id"];
}
Try this.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
[fetchRequest setEntity:entityDesc];
NSError *error = nil;
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"status_of_form==%#",#"Completed"];
[fetchRequest setPredicate:predicate];
NSArray *request = [context executeFetchRequest:fetchRequest error:&error];
if (!request.count==0) {
for (int i = 0; i<=request.count-1;i++) {
NSManagedObject *obj = [request objectAtIndex:i];
[loanIDArray addObject:[obj valueForKey:#"app_id"]];
}
}

Core data only returning null

I have a number of objects (NSManagedObject Subclass) which 'seem' to be created and saving correctly, however on reloading i can only get null from any of the variables within the objects.
The right number of objects are being saved, but none of the variables.
I've gone through the code several times, and I cant figure out if the problem is on the saving side or the loading side.
Would very much appreciate any thoughts!
Thanks in advance
//Create a route
- (CNSRoute *) createRoute
{
CNSRoute *p = [NSEntityDescription insertNewObjectForEntityForName:#"CNSRoute" inManagedObjectContext:context];
[allRoutes addObject:p];
//NSLog(#"Route: %#", p);
return p;
}
//Load all routes from core data
- (void) loadAllRoutes
{
NSLog(#"All Routes: %#", allRoutes);
if (!allRoutes) {
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *e = [[model entitiesByName] objectForKey:#"CNSRoute"];
[request setEntity:e];
NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey:#"name" ascending:YES];
[request setSortDescriptors:[NSArray arrayWithObject:sd]];
NSError *error;
NSArray *result = [context executeFetchRequest:request error:&error];
if (!result) {
[NSException raise:#"Fetch Failed" format:#"Reason: %#", [error localizedDescription]];
}
NSLog(#"LOAD RESULT: %#", result);
for (CNSRoute *route in result) {
NSLog(#"Loading Route... %#", [route name]);
}
allRoutes = [[NSMutableArray alloc] init];
[allRoutes setArray:result];
//NSLog(#"%#", allLocations);
}
}
//Save context
- (BOOL)saveChanges
{
NSError *err = nil;
BOOL successful = [context save:&err];
if (!successful) {
NSLog(#"ERROR SAVING: %#", [err localizedDescription]);
}
return successful;
}
//Save when application enters background
- (void)applicationDidEnterBackground:(UIApplication *)application
{
[[CNSTravelController sharedStore] saveChanges];
}

Resources