Load NSARRAY from NSCOREDATA - ios

I have save a NSARRAY in my nscoredatabase in binarydata type attribute saved with this code
AppDelegate *AppDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context =
[AppDelegate managedObjectContext];
//guardar array
NSData *arrayData = [NSKeyedArchiver archivedDataWithRootObject:roll];
NSManagedObject *newContact;
newContact = [NSEntityDescription
insertNewObjectForEntityForName:#"Horarios"
inManagedObjectContext:context];
[newContact setValue:arrayData forKey:#"valor"];
NSError *error;
[context save:&error];
But i dont know how to get it back from the data store to work again with this NSARRAY
Someone can help me?

Try this code:
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:#"Horarios"];
NSError *error;
NSArray *matches = [managedObjectContext executeFetchRequest:fetchRequest error:&error];

Solved adding this line
[fetchRequest setReturnsObjectsAsFaults:NO];

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

Delete specific data from specific entity from core data in objective c?

I have two entity in my core data named "History" and "Favorite". i want to delete some specific data like "Dhaka" from "History" entity. How to delete this. Thanks in advance.
Hope it will help you.
NSString* aType = #"History";
NSString *tp = #"Dhaka";
NSFetchRequest * request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:aType inManagedObjectContext:self.managedObjectContext]];
NSPredicate* predicate = [NSPredicate predicateWithFormat:#"(type == %#)",tp ]; //where type is the attribute
[request setPredicate:predicate];
NSArray* ar = [self.managedObjectContext executeFetchRequest:request error:nil];
NSLog(#"############# Data from DB : %#",ar);
for(id anObj in ar){
[managedObjectContext deleteObject:anObj];
}
[self.managedObjectContext save:nil];
predicate=nil;
try this:
objAppDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = [objAppDelegate managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:#"History"];
NSArray *recordArray =[[NSArray alloc]initWithArray:[context executeFetchRequest:request error:nil]];
objDataClass = [recordArray objectAtIndex:0]; // here objDataClass is a instance of DataClass derived from NSObject which define column name
[context deleteObject:objDataClass]; // Delete particular data with index
if ([context hasChanges])
{
[context save:nil];
}
else
{
NSLog(#"Object Deleted.....");
}
Hope it will help you. :)

How to update record in core data in iOS?

I hope it's a duplicate of other links like: How to update existing object in Core Data?
But my scenario is little bit different.
The thing is I created one Sample Core Data Project.
Step 1: I have 3 ViewController classes
In 1st Screen: I created one field in core data "password" ==> I saved using code like:
NSManagedObjectContext *context = [self managedObjectContext];
// Create a new userInfo
NSManagedObject *newuserInfo = [NSEntityDescription insertNewObjectForEntityForName:#"UserInfo" inManagedObjectContext:context];
[newuserInfo setValue:self.passwordTxtFldRef.text forKey:#"password"];
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
// NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
In 2nd Screen: I have two textfields like: Oldpassword & newpassword
. Here I saved old password in NSUserDefaults and in 2nd screen i checked the condition weather the oldpassword is correct or not --> It's perfect.
Here my requirement is I want to update Oldpassword to newpassword ---> in 2nd screen itself.
How can I do this? Can you please help me out regarding this?
Here i use code like:
-(void)getSavedDataFromCoreData{
NSManagedObjectContext *context = [self managedObjectContext];
NSEntityDescription *entitydesc = [NSEntityDescription entityForName:#"UserInfo" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
[request setEntity:entitydesc];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"password like %#",oldPasswordStr];
[request setPredicate:predicate];
NSError *error;
NSArray *matchingData = [context executeFetchRequest:request error:&error];
if(matchingData.count<=0){
//NSLog(#"Cancel");
}else{
for(NSManagedObject *obj in matchingData){
[obj setValue:alertTextField2.text forKey:#"password"];
}
[context save:&error];
NSMutableArray *array3 = [matchingData valueForKey:#"password"];
NSString *value3 = [array3 objectAtIndex:0];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setValue:value3 forKey:#"savedPassword"];
[defaults synchronize];
[self showGeneralAlertMessage:#"Password Changed Successfully" withTitle:#"Success"];
}
}
This will help you to update the value.
-(void)updateDataInCoreData
{
NSManagedObjectContext *context = appDelegate.managedObjectContext;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"User" inManagedObjectContext:context];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"number == %#",userDict[#"number"]];
[fetchRequest setPredicate:predicate];
[fetchRequest setFetchLimit:1];
[fetchRequest setEntity:entity];
NSError *error;
NSArray *arrResult = [context executeFetchRequest:fetchRequest error:&error];
User *entity1 = arrResult[0];
entity1.number = #"123456";
[appDelegate saveContext];
}

Update existing object in Core Data with reference to NSArray

I fetched the objects in an core data entity. Then I cross check with a NSArray and find out what are the existing objects in the data base.
Then I insert new objects to database. I am struggling in how to update existing objects in this code. Please help me to do it in best way.
// get manageObjectContext
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSArray *arrIds = [arr valueForKeyPath:#"anId"];
NSError *error;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"SomeEntity"
inManagedObjectContext:context];
[fetchRequest setEntity:entity];
fetchRequest.predicate = [NSPredicate predicateWithFormat:#"%K IN %#", #"anId", arrIds];
NSArray *existingItems = [context executeFetchRequest:fetchRequest error:&error];
//Get the existing ids:
NSArray *existingIds = [existingItems valueForKeyPath:#"anId"];
for (NSDictionary *item in arr) {
if ([existingItems containsObject:topic[#"anId"]]) {
// update exsising item
}
else{
// Insert new items done .........
}
you can use this code!!
AppDelegate *appDelegate =
[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context =
[appDelegate managedObjectContext];
NSEntityDescription *entityDesc =
[NSEntityDescription entityForName:#"Qr_code"
inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
NSPredicate *pred =
[NSPredicate predicateWithFormat:#"(user_ID=%#)",
kText];
[request setPredicate:pred];
matches = nil;
NSError *error;
updatedata = [context executeFetchRequest:request
error:&error];
if ([updatedata count] == 0) {
} else {
matches=updatedata[0];
}

Add multiple/sequential rows - populate DB in Coredata

How do you insert multiple/sequential new rows in coredata and xcode?
-(void)LoadDB{
CoreDataAppDelegate *appdelegate = [[UIApplication sharedApplication]delegate];
context = [appdelegate managedObjectContext];
NSManagedObject *newPref;
newPref = [NSEntityDescription
insertNewObjectForEntityForName:NSStringFromClass([Preference class])
inManagedObjectContext:context];
NSError *error;
[newPref setValue: #"0" forKey:#"pid"];
[context save:&error];
[newPref setValue: #"1" forKey:#"pid"];
[context save:&error];
}
The code above just over writes the previous entry. What is the correct procedure to insert the next row?
You need a new insert statement for each core data managed object. Otherwise you are only editing the existing MO. Also, you only need to save once at the end.
-(void)LoadDB{
CoreDataAppDelegate *appdelegate = [[UIApplication sharedApplication]delegate];
context = [appdelegate managedObjectContext];
NSManagedObject *newPref;
NSError *error;
newPref = [NSEntityDescription
insertNewObjectForEntityForName:NSStringFromClass([Preference class])
inManagedObjectContext:context];
[newPref setValue: #"0" forKey:#"pid"];
newPref = [NSEntityDescription
insertNewObjectForEntityForName:NSStringFromClass([Preference class])
inManagedObjectContext:context];
[newPref setValue: #"1" forKey:#"pid"];
// only save once at the end.
[context save:&error];
}

Resources