如何搜索核心数据实体并删除某些对象

时间:2010-11-15 14:49:03

标签: iphone objective-c core-data ios nspredicate

我不清楚如何从Core Data数据库中删除某些对象。我想我已经有了它,所以我可以找到对象,但不知道如何从Core Data中删除它们。在这个例子中,我正在实体新闻中搜索已过期的项目。我使用'expires'属性(int 32 unix时间戳)并查看该数字是否小于当前的unix时间戳。不确定NSPredicate是否正确。

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"News" inManagedObjectContext:self.managedObjectContext];
[request setEntity:entity]; 

// Set up predicate here?
NSPredicate *pred = [NSPredicate predicateWithFormat:@"expires < %i", dateInt]; // dateInt is a unix time stamp for the current time
[request setPredicate:predicate];

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"forename" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[sortDescriptors release];
[sortDescriptor release];
NSError *error;
NSMutableArray *mutableFetchResults = [[[managedObjectContext executeFetchRequest:request error:&error] mutableCopy] autorelease];
[request release];

// delete the found objects here?

2 个答案:

答案 0 :(得分:2)

为要删除的每个对象调用-[NSManagedObjectContext deleteObject:],然后提交更改。

答案 1 :(得分:0)

您可以使用iOS 9.0+macOS 10.11+tvOS 9.0+watchOS 2.0+

上提供的NSBatchDeleteRequest
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"expires < %i", dateInt];
NSFetchRequest *fetchRequest = [News fetchRequest];
[fetchRequest setPredicate:predicate];
// Create batch delete request
NSBatchDeleteRequest *deleteReq = [[NSBatchDeleteRequest alloc] initWithFetchRequest:fetchRequest];
NSError *error = nil;
NSBatchDeleteResult *deletedResult = [appDelegate.persistentContainer.viewContext executeRequest:deleteReq error:&error];
if (error) {
  NSLog(@"Unable to delete the data");
}
else {
  NSLog(@"%@ deleted", deleteReq.result);
}

Swift代码(来自上面的链接)

let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Employee")
fetch.predicate = NSPredicate(format: "terminationDate < %@", NSDate())
let request = NSBatchDeleteRequest(fetchRequest: fetch)

do {
    let result = try moc.execute(request)
} catch {
    fatalError("Failed to execute request: \(error)")
}

注意:

我在下面找到关于execute

moc的评论
  

将请求传递到商店而不影响托管对象上下文内容的方法。

这意味着moc中未保存的任何数据都不会受到影响。即如果您已创建/更新了属于删除请求条件且未在save上调用moc的实体,则该对象将不会被删除。