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

发布于 2024-10-02 03:58:08 字数 1085 浏览 1 评论 0原文

我不清楚如何从核心数据数据库中删除某些对象。我想我已经成功了,所以我可以找到这些对象,但不知道如何从核心数据中删除它们。在此示例中,我在实体新闻中搜索已过期的项目。我使用“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?

I'm unclear how to remove certain objects from Core Data database. I think I've got it working so I can find the objects, but don't know how to delete them from Core Data. In this example I'm searching the entity News for items which have expired. I use the 'expires' property (an int 32 unix time stamp) and see if the number is less than the current unix time stamp. Not sure if the NSPredicate is right in this.

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

初见你 2024-10-09 03:58:08

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

Call -[NSManagedObjectContext deleteObject:] for every object you want to delete, then commit the changes.

一向肩并 2024-10-09 03:58:08

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

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)")
}

注意:

我发现下面关于 mocexecute 的评论

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

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

You can use NSBatchDeleteRequest available on iOS 9.0+, macOS 10.11+, tvOS 9.0+, watchOS 2.0+

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 code (from the above link)

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)")
}

NOTE:

I found below comment about execute of moc

Method to pass a request to the store without affecting the contents of the managed object context.

Which means any unsaved data in moc won't be affected. i.e. if you've created/updated entity that falls in the delete request criteria and don't called save on moc then that object won't be deleted.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文