How to delete entries in core data - ios

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];
}
}

Related

coredata issue fetching data

I am getting only last record from coredata? below is the my code .
NSManagedObjectContext *context = ((AppDelegate*)[[UIApplication sharedApplication] delegate]).persistentContainer.viewContext;
NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:#"Company"
inManagedObjectContext:context];
[object setValue:#"infosys" forKey:#"cname"];
[object setValue:#"01" forKey:#"compID"];
[object setValue:#"Pune" forKey:#"locaation"];
[object setValue:#"wipro" forKey:#"cname"];
[object setValue:#"02" forKey:#"compID"];
[object setValue:#"Mumbai" forKey:#"locaation"];
NSError *error;
if (![context save:&error]) {
NSLog(#"Failed to save - error: %#", [error localizedDescription]);
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Company" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *result = [context executeFetchRequest:fetchRequest error:&error];
if (result.count<=0) {
NSLog(#"No User Found");
}
else{
NSString *cname;
NSString *compID;
NSString *locaation;
for (NSManagedObject *obj in result) {
cname=[obj valueForKey:#"cname"];
compID=[obj valueForKey:#"compID"];
locaation=[obj valueForKey:#"locaation"];
}
NSLog(#"Store Data = %#",[NSString stringWithFormat:#"%# %# %#",cname,compID,locaation]);
}
Add objects like this,
NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:#"Company" inManagedObjectContext:context];
[object setValue:#"infosys" forKey:#"cname"];
[object setValue:#"01" forKey:#"compID"];
[object setValue:#"Pune" forKey:#"locaation"];
NSManagedObject *object2 = [NSEntityDescription insertNewObjectForEntityForName:#"Company" inManagedObjectContext:context];
[object2 setValue:#"wipro" forKey:#"cname"];
[object2 setValue:#"02" forKey:#"compID"];
[object2 setValue:#"Mumbai" forKey:#"locaation"];
NSError *error;
if (![context save:&error]) {
NSLog(#"Failed to save - error: %#", [error localizedDescription]);
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Company" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *result = [context executeFetchRequest:fetchRequest error:&error];
if (result.count<=0) {
NSLog(#"No User Found");
}
else{
NSString *cname;
NSString *compID;
NSString *locaation;
for (NSManagedObject *obj in result) {
cname=[obj valueForKey:#"cname"];
compID=[obj valueForKey:#"compID"];
locaation=[obj valueForKey:#"locaation"];
NSLog(#"Store Data = %#",[NSString stringWithFormat:#"%# %# %#",cname,compID,locaation]);
}
}

Getting Null Value From Database NSManagedObject

I am developing iOS app, which fetch data from Web Services and save it to local database and uses it various views as needed. The data is fetch from Web Service and save to database correctly. But while accessing data from NSManagedObject it show FAULT and the consequent NSDictionary shows null Values
The code follows:-
-(void)SaveData:(NSInteger)menuId categoryID:(NSInteger)catID caption:(NSString *)title parentID:(NSInteger)parentID
{
BBAppDelegate *appDelegate = [[BBAppDelegate alloc]init];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSManagedObject *userobj = [NSEntityDescription insertNewObjectForEntityForName:tableName
inManagedObjectContext:context];
[userobj setValue:[NSNumber numberWithInt:menuId] forKey:#"id"];
[userobj setValue:[NSNumber numberWithInt:catID] forKey:#"catid"];
[userobj setValue:[NSNumber numberWithInt:parentID] forKey:#"parentid"];
[userobj setValue:title forKey:#"caption"];
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
NSLog(#"app dir: %#",[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]);
}
-(NSArray *)fetchedData{
BBAppDelegate *appdelegate = [[BBAppDelegate alloc]init];
NSManagedObjectContext *context = [appdelegate managedObjectContext];
NSFetchRequest *readData = [[NSFetchRequest alloc] init];
[readData setReturnsObjectsAsFaults:NO];
NSEntityDescription *entity = [NSEntityDescription
entityForName:tableName inManagedObjectContext:context];
[readData setEntity:entity];
NSError *error = nil;
NSArray *results = [context executeFetchRequest:readData error:&error];
// for (Test *test in array)
// {
// NSLog(#"Test: %# ", test.text);
// }
NSLog(#"%#",results);
return results;
}
-(void)removeData{
BBAppDelegate *appdelegate = [[BBAppDelegate alloc]init];
NSManagedObjectContext *context = [appdelegate managedObjectContext];
NSFetchRequest *delData = [[NSFetchRequest alloc]init];
[delData setEntity:[NSEntityDescription entityForName:tableName inManagedObjectContext:context]];
[delData setIncludesPropertyValues:NO];
NSError *error = nil;
NSArray *result = [context executeFetchRequest:delData error:&error];
for (NSManagedObject *value in result) {
[context deleteObject:value];
}
NSError *saveError = nil;
[context save:&saveError];
}
-(void)table:(NSString *)nameTable{
tableName =nameTable;
}
- (instancetype)initWithTableName:(NSString *)tablename
{
[self table:tablename];
return self;
}
-(NSMutableArray *)buldMenu{
NSArray *array = [self fetchedData];
return [self getmenus:0 arr:array];
}
-(NSMutableArray *)getmenus:(NSInteger)parentID arr: (NSArray *)array
{
NSMutableArray *aray = [[NSMutableArray alloc]init];
for (NSManagedObject *dic in array) {
if (dic.faultingState != 0) {
NSLog(#"%lu",(unsigned long)dic.faultingState);
//return nil;
}
NSArray *keys = [[[dic entity] attributesByName] allKeys];
NSLog(#"%#",keys);
NSDictionary *dict = [dic dictionaryWithValuesForKeys:keys];
NSLog(#"%#",dic);
NSLog(#"%#",dict);
NSInteger pID = [[dict objectForKey:#"parentid"]integerValue];
if (pID == parentID) {
BBMenuEntry *entryMenu = [[BBMenuEntry alloc]init];
entryMenu.menuID = [[dict objectForKey:#"id"]integerValue];
entryMenu.catID = [[dict objectForKey:#"catid"]integerValue];
entryMenu.caption = [dict objectForKey:#"caption"];
entryMenu.subMenus = [self getmenus:entryMenu.menuID arr:array];
[aray addObject:entryMenu];
}
}
return aray;
}

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"]];
}
}

Strange behavior in deleting core data contents

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");
} }

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