我在我的应用程序中使用核心数据,当涉及到从核心数据存储中删除某些行或条目时,我感到很困惑。我像这样将一些产品插入到存储中:
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'
我将非常感谢一些示例代码,因为我似乎无法弄清楚这一点。
感谢您的帮助。
最佳答案
正如@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];
}
下次保存上下文时,对象的数据将从持久存储文件中删除。
关于iphone - 从核心数据中删除特定条目/行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6524876/