简体   繁体   中英

My database getting updated while updating NSManageObject in the local array

In my iOS app, I am using Coredata to store data. In my application I have one HomeVC, this HomeVC contains list foods with checkmark button. To do this, I have created 'Food' entity with name and selected attributes. To display a list of foods in the HomeVC, I fetched data from the database and stored into the local array and bind this array to the tableView. When user clicked on check button I have updated selected attribute within this local array. All is working fine.

I am facing problem while updating selected attribute within the local array this attribute also getting changed into the database.

EDIT:

NSEntityDescription* entityDesc = [NSEntityDescription entityForName:entityName inManagedObjectContext:self.managedObjectContext];
NSFetchRequest* fetchReq = [[NSFetchRequest alloc]init];
[fetchReq setEntity:entityDesc];

// Fetching rows from database
NSArray* results = [self.managedObjectContext executeFetchRequest:fetchReq error:nil];

 //Assigning results to local array
_localArray = [NSMutableArray arrayWithArray:results];

Anybody knows how to solve this?

So you want to change the data, but not store the changes and instead discard them later? A strange requirement, but of course it can be done.

You need to create a new managed object context which could have the main context of your app as the parent context. You can then choose:

  • save the context (the changes will be "pushed up" to the parent context, but not saved to the database until the main context is saved)
  • discard the context (nothing is saved)

To create the child context:

let childContext = 
       NSManagedObjectContext(concurrencyType:.MainQueueConcurrencyType)
childContext.parentContext = mainContext

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM