从Core-Data中删除特定条目/行

时间:2011-06-29 17:35:57

标签: iphone objective-c xcode core-data nsmanagedobject

我在我的应用程序中使用核心数据,当涉及从核心数据存储中删除某些行或条目时,我感到很困惑。我将一些产品插入存储器中,如下所示:

NSManagedObject *Product = [NSEntityDescription insertNewObjectForEntityForName:@"Product" inManagedObjectContext:context];
[Product setValue:[NSNumber numberWithFloat:id] forKey:@"pid"];
[Product setValue:[NSNumber numberWithFloat:quantity] forKey:@"pquantity"];

这适用于插入。但是,稍后在应用程序中,我想删除条目,例如,pid是53.如何才能删除此行/条目?等效的SQL类似于:

DELETE from Product WHERE pid = '53'

我非常感谢一些示例代码,因为我似乎无法想出这个代码。

感谢您的帮助。

8 个答案:

答案 0 :(得分:42)

正如@Nektarios所说,你在这里处理对象,所以你想要找到一个具有特定属性值的对象。你有一个获取请求和一个谓词。

  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

fetchedProducts数组将包含Product属性等于pid的实体soughtPid的所有对象。请注意,谓词在逻辑上与SQL中的where子句完成相同的功能。

获得对象后,您只需告诉上下文删除它们:

  for (NSManagedObject *product in fetchedProducts) {
    [context deleteObject:product];
  }

下次保存上下文时,对象的数据将从持久性存储文件中删除。

答案 1 :(得分:13)

与Sqlite的“从tableName WHERE条件中删除”一样,您没有从CoreData中删除MULTIPLE个对象的单一步骤。

CoreData 中,首先您必须使用NSFetchRequestNSPredicate

获取必须删除的对象
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];

然后,您应该迭代遍历每个NSManagedObject并从deleteObject:致电NSManagedObjectContext

if (!error && result.count > 0) {
    for(NSManagedObject *managedObject in result){
        [managedObjectContext deleteObject:managedObject];
    }

    //Save context to write to store
    [managedObjectContext save:nil];
}

答案 2 :(得分:6)

请记住将Core Data视为图形而不是DB,因此行的概念不适用。相反,您想要从图表中删除特定对象。

您使用insertNewObjectForEntityForName:inManagedObjectContext:插入它。使用deleteObject:删除它,例如:

[aContext deleteObject:aManagedObject];

在你的情况下,

[context deleteObject:Product];

祝你好运

请参阅Apple的explanation here

注意:根据您的方案删除时,可能会产生不同的含义。例如,它可以删除Core Data对象图的子路径下的所有内容。确保在设计关于应该如何工作的模式时要认真思考。如果你设置正确,这对你来说是一个巨大的优势。

答案 3 :(得分:6)

使用此方法:

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

答案 4 :(得分:2)

使用此

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

答案 5 :(得分:1)

我一直在使用UITableView滑动删除几天,最终我完成了任务。

tableview由核心数据对象的数据填充。已使用的委托方法是:

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

希望能帮助别人。

答案 6 :(得分:0)

非常简单,其中DatabaseInfo是我的实体的名称,其中filename是一个属性

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]    

}

答案 7 :(得分:0)

在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{

                }
            }