我不知道您是否查看了adding and deleting 对象部分的核心数据编程指南。
编辑
我已将其修改为从名称数组中删除。再次;使用Predicate Programming Guide 不到 5 分钟。
- (void)removeObjectsWithNames:(NSArray *)nameArray {
// Get the moc and prepare a fetch request for the required entity
NSManagedObjectContext *moc = [self managedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Project" inManagedObjectContext:moc];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];
// Create a predicate for an array of names.
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name IN %@", nameArray];
[request setPredicate:predicate];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
// Execute the fetch request put the results into array
NSError *error = nil;
NSArray *resultArray = [moc executeFetchRequest:request error:&error];
if (resultArray == nil)
{
// Diagnostic error handling
NSAlert *anAlert = [NSAlert alertWithError:error];
[anAlert runModal];
}
// Enumerate through the array deleting each object.
// WARNING, this will delete everything in the array, so you may want to put more checks in before doing this.
For (JGManagedObject *objectToDelete in resultArray ) {
// Delete the object.
[moc deleteObject:objectToDelete];
}
}
2009 年 10 月 10 日编辑 - 添加 Joshua 尝试过的内容。
for(NSString *title in oldTasks) { // 1
// Get the moc and prepare a fetch request for the required entity
NSManagedObjectContext *moc = [self managedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"projects" inManagedObjectContext:moc];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];
// Create a predicate for an array of names.
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title IN %d", oldTasks]; // 2
[request setPredicate:predicate];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
// Execute the fetch request put the results into array
NSError *error = nil;
NSArray *resultArray = [moc executeFetchRequest:request error:&error];
if (resultArray == nil)
{
// Diagnostic error handling
NSAlert *anAlert = [NSAlert alertWithError:error];
[anAlert runModal];
}
JGManagedObject *objectToDelete = [resultArray objectAtIndex:0];
// Delete the object.
[moc deleteObject:objectToDelete];
}
备注
我已经突出显示了两行。
您将我的示例粘贴为 for 循环而不是函数调用。这只是一次取下一个字符串并将它们传递给方法。在我的示例中,我传入了一个您想要匹配的字符串数组。
这是您遇到问题的地方。如果您费心阅读谓词编程指南,就在顶部的谓词基础部分,它说它希望与它一起使用的类应该是 KVC 兼容的。这就是您收到有关 KVC 合规性错误的原因。您正在尝试搜索标题 IN...,但标题不是您模型的属性。
我认为您可能对谓词的作用感到困惑。看看我写的示例代码。
首先,我创建一个 Fetch 请求,它将从“项目”实体中选择对象。
其次,我创建了一个谓词,该谓词针对 fetch 请求返回的每个对象,获取 'name' 属性的值并将其与 'namesArray' 中对象的值进行比较
第三,我正在创建一个排序描述符,它将根据“名称”属性按升序对结果进行排序。
然后,一旦我设置了这个获取请求,我就在 moc 上运行它,它会返回一个符合这些条件的对象数组。