2011-06-29 25 views
23

Estoy usando datos principales en mi aplicación, y estoy confundido cuando se trata de eliminar ciertas filas o entradas del almacenamiento de datos centrales. Inserto algunos productos en el almacenamiento de la siguiente manera:Eliminar una entrada/fila específica de Core-Data

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

Esto funciona bien para la inserción. Sin embargo, más adelante en la aplicación, quiero eliminar la entrada donde, por ejemplo, el pid es 53. ¿Cómo voy a eliminar solo esta fila/entrada? El equivalente SQL sería algo así como:

DELETE from Product WHERE pid = '53' 

Les agradecería mucho un código de ejemplo, ya que parece que no puede imaginar éste.

Gracias por cualquier ayuda.

Respuesta

6

Recuerda pensar en los datos principales como un gráfico y no como un DB, por lo que el concepto de filas no se aplica. En cambio, desea eliminar un objeto específico del gráfico.

Has usado insertNewObjectForEntityForName:inManagedObjectContext: para insertarlo. Utilice deleteObject: para eliminarlo, como por ejemplo:

[aContext deleteObject:aManagedObject];

En su caso,

[context deleteObject:Product];

Buena suerte

Sede de Apple explanation here

Nota: cuando se elimina, dependiendo de tu esquema, eso puede tener implicaciones diferentes s. Por ejemplo, podría eliminar todo lo que esté más abajo en la ruta secundaria de su gráfico de objetos de Core Data. Asegúrese de pensar detenidamente al diseñar su esquema sobre cómo debería funcionar. Si lo configuras bien, esto puede ser una gran ventaja para ti.

+0

gran conocimiento que han compartido .. –

42

Como dijo @Nektarios, usted está tratando con objetos aquí, por lo que desea encontrar un objeto que tenga un valor de atributo particular. Tú eso con una solicitud de búsqueda y un predicado.

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 

La matriz fetchedProducts contendrá todos los objetos de la entidad Product cuyo atributo es igual a pidsoughtPid. Tenga en cuenta que el predicado cumple la misma función lógicamente que la cláusula where en SQL.

Una vez que tenga los objetos que acaba de decir el contexto para eliminarlos:

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

La próxima vez que guarde el contexto, los datos del objeto se eliminarán del archivo de almacenamiento persistente.

+0

que editar un código de acuerdo a mi requerimiento, pero este código funciona para mí, gracias @TechZen – MahboobiOSDeveloper

+0

excelente trabajo u han hecho .. Funciona bien –

+0

¿Puedes escribir el código rápidamente? – amish

2

uso de este

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

El uso de este método:

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

bastante simple donde DatabaseInfo es el nombre de mi entidad, donde nombre de archivo es un atributo

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) 
{ 
    [email protected]"No Match Found"; 
} 
else{ 
    matches = objects[0]; 

    [context deleteObject:matches]  

} 
11

Como SQLite de " ELIMINAR de tableName WHERE condición ", no tiene un solo paso para eliminar los objetos MULTIPLE de CoreD ata

En CoreData, primero hay que ir a buscar objetos que tiene que ser eliminado, utilizando NSFetchRequest y 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]; 

Entonces, usted debe iterate a través de cada NSManagedObject y llame deleteObject: de su NSManagedObjectContext .

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

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

Sí, esto está funcionando perfecto. – ravinder521986

1

He estado trabajando con el deslizamiento de UITableView para eliminarlo durante unos días, eventualmente hice algunas cosas.

La tabla vista está poblada por los datos del objeto de datos central. Los métodos de delegado se han utilizado son:

-(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 someone.

0

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

       } 
      } 
+0

Este código no elimina la fila, sino que hace que 'currentItemId' = 0. Estoy buscando eliminar la fila en su lugar. – amish

Cuestiones relacionadas