i want to know how can I update a coredata record that was selected from a tableView
my code to save the coredata is:
- (IBAction)juardar:(id)sender {
NSUserDefaults *defs=[NSUserDefaults standardUserDefaults];
NSString *sedef_mat=[NSString stringWithFormat:#"%#",[defs objectForKey:#"Materia"]];
//NSLog(#"%#",sedef_mat);
NSManagedObjectContext *context = [self managedObjectContext];
// Create a new managed object
NSManagedObject *newtarea = [NSEntityDescription insertNewObjectForEntityForName:#"Tareas" inManagedObjectContext:context];
[newtarea setValue:self.Nombre.text forKey:#"nombre"];
[newtarea setValue:self.Descripcion.text forKey:#"descripcion"];
[newtarea setValue:sedef_mat forKey:#"materia"];
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
//NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
}
Thanks
Just set the new values then save the context just as you did above. But you'll be working with the fetched results:
for (Tareas *object in fetchedResultsController.fetchedObjects)
{
Tareas *t = (Tareas *)object;
if ([t.nombre isEqualToString:#"NewValue1"])
{
Tareas.nombre = #"NewValue1";
Tareas.description = #"NewValue2";
Tareas.materia = #"NewValue3";
}
}
then save context like you did above:
if (![context save:&error])
etc.
Related
This how NSManagedObject is created
NSEntityDescription *entity = [NSEntityDescription entityForName:strEntityName inManagedObjectContext:managedObjContext];
NSManagedObject * managedObject = (NSManagedObject *)[[NSClassFromString(strEntityName) alloc] initWithEntity:entity insertIntoManagedObjectContext:managedObjContext];
//values are mapped into this object
Now save NSManagedObject to persistent store and fetching currently inserted object like this :
NSError *error;
BOOL isDone = [managedObjectContext save:&error];
//BOOL isDone = [managedObjectContext obtainPermanentIDsForObjects:[NSArray arrayWithObjects:tempManagedObject, nil] error:&error];
if (isDone && error == nil){
//fetch last inserted object here
//make fetch request
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:strEntityName];
//make query using fetch request in context
NSError *error;
NSArray *arrFetchRequest = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (arrFetchRequest.count>0){
//This is last inserted object
NSManagedObject *managedObject = [arrFetchRequest lastObject];
return managedObject;
}
}
I have also refered Swift - How to get last insert id in Core Data, store it in NSUserDefault and predicate. But it will not have permanent object ID in NSManagedObject as we are saving temparory ID and fetching using that and we don't have permanent ID at all.
Canyone share any other options?
While inserting NSManagedObject in context, it will have temporaryID (this means it has not been saved to database).
So need to get permanentID (this means it has been saved to database) for NSManagedObject in context, use obtainPermanentIDsForObjects and same NSManagedObject will have permanentID
if (insertManagedObject)
{
NSLog(#"Before %# : %d",insertManagedObject.objectID,insertManagedObject.objectID.isTemporaryID);
//Obtain permanentID for object
NSError *error;
BOOL hasObtainedPermanentID = [managedObjectContext obtainPermanentIDsForObjects:[NSArray arrayWithObjects:insertManagedObject, nil] error:&error]; //;
//check if its done
if (hasObtainedPermanentID && error == nil){
NSLog(#"After %# : %d",insertManagedObject.objectID,insertManagedObject.objectID.isTemporaryID);
//check context has changes and is saved in context
if ([managedObjectContext hasChanges] && [managedObjectContext save:&error])
{
return insertManagedObject;
}
}
}
I am having data Like This:
Appliance Average Power Rating (Watts) Alternate Power Rating (Watts)
Fridge/Refrigerator 120 55
Microwave 1000 1000
Mixie 700 200
Roti Maker 30 300
I want to store this data into my entity in CoreData. Just I have created an entity called EY_Appliance with attributes applianceId, applianceName, watts and amountPerWatts.
You have to write code in this way. This will insert new Object for your entity with following attributes. You can edit it as per your requirement.
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *powerDesc = [NSEntityDescription insertNewObjectForEntityForName:#"EY_Appliance" inManagedObjectContext:context];
[powerDesc setValue:self.applianceId.text forKey:#"applianceId"];
[powerDesc setValue:self.applianceName.text forKey:#"applianceName"];
[powerDesc setValue:self.watts.text forKey:#"watts"];
[powerDesc setValue:self.amountPerWatts.text forKey:#"amountPerWatts"];
// Save the context
NSError *error = nil;
if (![context save:&error]) {
NSLog(#"Saving Failed!, Error and its Desc %# %#", error, [error localizedDescription]);
}
For that you can create and add the core data object as follows
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:#"EY_Appliance" inManagedObjectContext:context];
[object setValue:self.applianceIdValue forKey:#"applianceId"];
[object setValue:self.applianceNameValue forKey:#"applianceName"];
[object setValue:self.wattsValue forKey:#"watts"];
[object setValue:self.amountPerWattsValue forKey:#"amountPerWatts"];
NSError *error = nil;
if (![context save:&error]) {
NSLog(#"Saving Failed with error %#", error);
}
so I'm trying to overwrite/update a value saved from core data. when the back button is pressed (gets the textfield data and then overwrites the data using that). But it just keeps adding new data in. Here's my code in the back button:
The IF statement is just checking what the index is so it knows which view controller to go back to. goBackMVC just takes it back to a certain view controller.
- (IBAction)btnBack:(UIBarButtonItem *)sender {
if (self.viewControllerIndex == 3) {
NSLog(#"test");
[self saveDataMethod];
[self goBackMVC];
[self.navigationController popViewControllerAnimated:YES];
}
saveDataMethod:
- (void) saveDataMethod {
NSManagedObjectContext *context = [self managedObjectContext];
// Create a new managed object
FavouriteItem *favouriteItem = [NSEntityDescription insertNewObjectForEntityForName:#"FavouriteEntity" inManagedObjectContext:context];
favouriteItem.webName = self.txtName.text;
favouriteItem.webURL = self.txtURL.text;
favouriteItem.imageURL = self.txtImageURL.text;
NSLog(#"favouriteItem.webName %#", favouriteItem.webName);
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
}
My question is how can I overwrite the data instead of just adding it? Thanks.
edit: I've searched around and a lot of solutions have arrays, but I'm not allowed to use arrays
This is because you insert a new entity to your core data :
FavouriteItem *favouriteItem = [NSEntityDescription insertNewObjectForEntityForName:#"FavouriteEntity" inManagedObjectContext:context];
Instead fetch the required entity :
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:[NSEntityDescription entityForName:#"Favorits" inManagedObjectContext:context]];
To get the required entity create an NSPredicate instance to filter the required entity (in case you have more than one) and use it in your request :
NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:<Your filter string>];
[fetchRequest setPredicate:filterPredicate];
NSError *error = nil;
NSArray* entities = [context executeFetchRequest:fetchRequest error:&error];
if ([entities count] == 1) {
// Get the entity and update necessary fields and save in context
}
I'm still new at Core Data.
I'm trying to loop three times over an array and at each loop, I'm saving the index number.
But it's only showing the last index number when fetching the results. It's overriding everything that was inserted before.
My code is written in the AppDelegate.
Here's my code:
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *tagsDB = [NSEntityDescription insertNewObjectForEntityForName:#"Tags" inManagedObjectContext:context];
for (int i = 0 ; i < 3 ; i++)
{
[tagsDB setValue:i forKey:#"ID"];
}
[self saveContext];
...
- (void)saveContext
{
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
}
You have to create your entity for each value.
NSManagedObjectContext *context = [self managedObjectContext];
for (int i = 0 ; i < 3 ; i++)
{
NSManagedObject *tagsDB = [NSEntityDescription insertNewObjectForEntityForName:#"Tags" inManagedObjectContext:context];
[tagsDB setValue:i forKey:#"ID"];
}
[self saveContext];
In your for loop - the code that gets reiterated simply changes the value of the new inserted item. What you need to be doing in the for loop is insertNewObjectForEntityForName which will insert a new, separate entity for each iteration.
I'm making the app using core-data.
It's facebook app, so I saved the User information to core-data.
And I wanna add the profile picture to user information data.
for (UserInfo *info in fetchedObjects) {
if ([info.fbId isEqualToString:delegate.currentUserInfo.fbId]) {
info.details.photos.image = [NSData dataWithContentsOfURL:url];
info.details.photos.imageId = [result objectForKey:#"id"];
info.details.photos.details = info.details;
delegate.currentUserInfo = info;
for (UserInfo *info in fetchedObjects) {
NSLog(#"currentUserInfo : %#", info);
NSLog(#"curretnUserDetails : %#", info.details);
NSLog(#"currentUserPhoto : %#", info.details.photos);
}
if (![context save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
}
}
Like this, I add the data to the core-data (relationshop named photos) corresponding to FB user ID.
As a result, NSLog in the middle shows well photoInfo data, but when I restart my app, there is no photo data.
I didn't solve this problem for a few days. Help me!
-edited
DataModel is organized like this picture.
I'm using only one context, and I'm novice so I can't understand all of thankful comment.
-edited2
if (!beExist) {
UserInfo *userInfo = [NSEntityDescription insertNewObjectForEntityForName:#"UserInfo" inManagedObjectContext:context];
userInfo.name = [myInfoDic objectForKey:#"name"];
userInfo.fbId = [myInfoDic objectForKey:#"id"];
userInfo.type = #"user";
UserDetails *userDetails = [NSEntityDescription insertNewObjectForEntityForName:#"UserDetails" inManagedObjectContext:context];
userDetails.gender = [myInfoDic objectForKey:#"gender"];
userDetails.work = [[[[myInfoDic objectForKey:#"work"] objectAtIndex:0] objectForKey:#"employer"] objectForKey:#"name"];
NSArray *eduArray = [myInfoDic objectForKey:#"education"];
userDetails.education = [[[eduArray objectAtIndex:eduArray.count-1] objectForKey:#"school"] objectForKey:#"name"];
userDetails.birthday = [myInfoDic objectForKey:#"birthday"];
userDetails.location = [[myInfoDic objectForKey:#"location"] objectForKey:#"name"];
PhotoInfo *photoInfo = [NSEntityDescription insertNewObjectForEntityForName:#"PhotoInfo" inManagedObjectContext:context];
userDetails.info = userInfo;
userInfo.details = userDetails;
userInfo.details.photos = photoInfo;
photoInfo.details = userDetails;
delegate.currentUserInfo = userInfo;
if (![context save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
I saved User information like this.
I created context in AppDelegate. I made the project for Core data, so Xcode made that code.
I can see this log
2012-05-04 00:40:58.997 Feek[16423:fb03] currentUserPhoto : <PhotoInfo: 0x6d15d60> (entity: PhotoInfo; id: 0x6d18550 <x-coredata://2ED200FE-D799-4C66-A0AC-5BE1BC426439/PhotoInfo/p1> ; data: {
details = "0x8830ca0 <x-coredata://2ED200FE-D799-4C66-A0AC-5BE1BC426439/UserDetails/p1>";
image = <ffd8ffe0 00104a46 49460001 02000001 00010000 fffe0004 2a00ffe2 021c4943 435f5052 4f46494c 45000101 0000020c 6c63>;
imageId = 334168116641714;
})
I think that this is core data accept data, but it doesn't remain after killing my app.