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

查看:113
本文介绍了从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说,你在这里处理对象,查找具有特定属性值的对象。你有一个获取请求和一个谓词。

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 array将包含 pid 属性等于的所有对象 / code>。注意,谓词在逻辑上与SQL中的其中子句具有相同的功能。

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天全站免登陆