I'm using core data in my app, and i'm confused when it comes to removing certain rows or entries from the core data storage. I insert some products in to the storage like so:
NSManagedObject *Product = [NSEntityDescription insertNewObjectForEntityForName:@"Product" inManagedObjectContext:context];
[Product setValue:[NSNumber numberWithFloat:id] forKey:@"pid"];
[Product setValue:[NSNumber numberWithFloat:quantity] forKey:@"pquantity"];
This works fine for insertion. However, later in the app, I want to remove the entry where for example, the pid is 53. How would I go about removing only this row/entry? The equivalent SQL would be something like:
DELETE from Product WHERE pid = '53'
开发者_Python百科
I would greatly appreciate some example code, as I can't seem to figure this one out.
Thanks for any help.
As @Nektarios said, you are dealing with objects here so you want to find an object that has a particular attribute value. You that with a fetch request and a predicate.
NSNumber *soughtPid=[NSNumber numberWithInt:53];
NSEntityDescription *productEntity=[NSEntityDescription entityForName:@"Product" inManagedObjectContext:context];
NSFetchRequest *fetch=[[NSFetchRequest alloc] init];
[fetch setEntity:productEntity];
NSPredicate *p=[NSPredicate predicateWithFormat:@"pid == %@", soughtPid];
[fetch setPredicate:p];
//... add sorts if you want them
NSError *fetchError;
NSArray *fetchedProducts=[self.moc executeFetchRequest:fetch error:&fetchError];
// handle error
The fetchedProducts
array will contain all the objects of the entity Product
whose pid
attribute equals soughtPid
. Note that the predicate fulfills the same function logically as the where
clause in SQL.
Once you have the objects you just tell the context to delete them:
for (NSManagedObject *product in fetchedProducts) {
[context deleteObject:product];
}
When you next save the context, the object's data will be deleted from the persistent store file.
Like Sqlite's "DELETE from tableName WHERE condition", you have no single step to delete MULTIPLE
objects from CoreData.
In CoreData, first you have to fetch objects that has to be deleted, using NSFetchRequest
and NSPredicate
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"EntityName"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"propertyName == %@", value];
[request setPredicate:predicate];
NSError *error = nil;
NSManagedObjectContext *managedObjectContext;//Get your ManagedObjectContext;
NSArray *result = [managedObjectContext executeFetchRequest:request error:&error];
Then, you should iterate through every NSManagedObject
and call deleteObject:
from your NSManagedObjectContext
.
if (!error && result.count > 0) {
for(NSManagedObject *managedObject in result){
[managedObjectContext deleteObject:managedObject];
}
//Save context to write to store
[managedObjectContext save:nil];
}
Remember to think of Core Data as a graph and not a DB, so the concept of rows doesn't apply. Instead, you want to remove a specific object from the graph.
You used insertNewObjectForEntityForName:inManagedObjectContext:
to insert it. Use deleteObject:
to delete it, such as:
[aContext deleteObject:aManagedObject];
In your case,
[context deleteObject:Product];
Good luck
See Apple's explanation here
Note: when you delete, depending on your scheme, that can have different implications. For example it could delete everything further down the child-path of your Core Data object graph. Make sure you think hard when designing your schema about how that should work. If you set it up right, this can be a huge advantage to you.
Use this method:
+ (void)Deletebeer:(NSString*)m_Beerid
{
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *productEntity=[NSEntityDescription entityForName:@"Beers" inManagedObjectContext:context];
NSFetchRequest *fetch=[[NSFetchRequest alloc] init];
[fetch setEntity:productEntity];
NSPredicate *p=[NSPredicate predicateWithFormat:@"m_Beerid == %@", m_Beerid];
[fetch setPredicate:p];
//... add sorts if you want them
NSError *fetchError;
NSError *error;
NSArray *fetchedProducts=[context executeFetchRequest:fetch error:&fetchError];
for (NSManagedObject *product in fetchedProducts) {
[context deleteObject:product];
}
[context save:&error];
}
use this
Entity *entity = (Entity *)[NSEntityDescription insertNewObjectForEntityForName:@"Entity" inManagedObjectContext:managedObjectContext];
[entity setTimeStamp:[NSDate date]];
NSError *error;
if ([managedObjectContext save:&error]) {
}
[eventArray delete:<#(id)sender#>];
[self.tableView reloadData];
I have been working with UITableView swipe to delete for a few day, eventually I got things done.
The tableview is populated by the data from core data object. Delegate methods has been used are:
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSectin:(NSInteger)section**
{
reture [_arrData count];
}
-(NSInteger)numberOfSectionInTablesView:(UITableView *)tableView
{
return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellID = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if(cell == nil){
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStleDefault reuseIdentifier:cellID];
}
cell.textLable.text = [_arrData objectAtIndex:indexPath.row];
return cell;
}
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
return YES;
}
-(NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewRowAction *delete = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"Delete" handler:^(UITableViewRowAction *action,NSIndexPath *indexPath){
//**************load address **************
NSError *error;
AppDelegate *sharedDelegate = [AppDelegate appDelegate];
NSManagedObjectContext *context = [sharedDelegate managedObjectContext];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"data" inManagedObjectContext:context];
NSFetchRequest *fetchReuqets = [[NSFetchRequest alloc] init];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"lat == %@", [_arrLat objectAtIndex:indexPath.row]];
[fetchReuqets setPredicate:predicate];
NSLog(@"delete %@",[_arrLat objectAtIndex:indexPath.row]);
[fetchReuqets setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchReuqets error:&error];
NSLog(@"number of filtered objects=%ld",fetchedObjects.count);
if(!error && fetchedObjects.count>0){
for (NSManagedObject *addr in fetchedObjects){
[context deleteObject:addr];
NSLog(@"delete addr %@",addr);
}
[context save:&error];
}
//***************core data**************************
[_arrData removeObjectAtIndex:indexPath.row];
[tableView reloadData];
}];
delete.backgroundColor = [UIColor redColor];
return @[delete];
}
Hopefully help somebody.
Pretty Simple where DatabaseInfo is the name of my entity, where filename is an attribute
CoreAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Contacts" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
NSPredicate *pred= [NSPredicate predicateWithFormat:@"(filename = %@)", @"Thankyou"];
[request setPredicate:pred];
NSManagedObject *matches = nil;
NSError *error;
NSArray *objects = [context executeFetchRequest:request error:&error];
if([objects count] == 0)
{
_label1.text=@"No Match Found";
}
else{
matches = objects[0];
[context deleteObject:matches]
}
In Swift 3:
if let dataAppDelegatde = UIApplication.shared.delegate as? AppDelegate {
let mngdCntxt = dataAppDelegatde.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ItemCart")
let predicate = NSPredicate(format: "itemId = %i", Int(currentItemID)!)
print(currentItemID)
fetchRequest.predicate = predicate
do{
let result = try mngdCntxt.fetch(fetchRequest)
print(result.count)
if result.count > 0{
for object in result {
print(object)
mngdCntxt.delete(object as! NSManagedObject)
}
}
}catch{
}
}
精彩评论