从 Core-Data 中删除特定条目/行 [英] Removing a specific entry/row from Core-Data

查看:22
本文介绍了从 Core-Data 中删除特定条目/行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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'

我非常感谢一些示例代码,因为我似乎无法弄清楚这一点.

I would greatly appreciate some example code, as I can't seem to figure this one out.

感谢您的帮助.

推荐答案

正如@Nektarios 所说,您在这里处理对象,因此您想找到具有特定属性值的对象.你用一个 fetch 请求和一个谓词.

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

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

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.

这篇关于从 Core-Data 中删除特定条目/行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆