objective-c CoreData:如何使用谓词获取特定对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2306137/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 22:58:24  来源:igfitidea点击:

CoreData: How to fetch a specific object using a predicate

objective-ciphonecore-data

提问by fabian

The situation:

情况:

I fetch a complete table from my sqllite core data database and show it in a TableView like this:

我从我的 sqllite 核心数据数据库中获取一个完整的表,并将其显示在一个 TableView 中,如下所示:

NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyTable"
                                          inManagedObjectContext:managedObjectContext];

The Challenge:

挑战:

How do I get the EntryID and fetch the specific entry from the database (e.g. if i click on an entry)? I think this goes in the right direction?

如何获取 EntryID 并从数据库中获取特定条目(例如,如果我单击一个条目)?我认为这朝着正确的方向发展?

NSPredicate *predicate = [NSPredicate predicateWithFormat: @"(id = %@)", myEntryID];

回答by MrMage

If you have an entry object called entry, it would be a predicate like this:

如果您有一个名为 的条目对象entry,它将是这样的谓词:

NSPredicate *predicate = [NSPredicate predicateWithFormat: @"(SELF = %@)", entry];

Which is roughly equivalent to

这大致相当于

NSPredicate *predicate = [NSPredicate predicateWithFormat: @"(objectID = %@)", entry.objectID];

For a NSManagedObjectID, you get something like:

对于 a NSManagedObjectID,你会得到类似的东西:

NSPredicate *predicate = [NSPredicate predicateWithFormat: @"(objectID = %@)", myEntryID];

回答by Maciek Czarnik

This is proper predicate:

这是正确的谓词:

[NSPredicate predicateWithFormat:@"SELF = %@", objectID];

Where objectIDis NSManagedObjectIDinstance.

哪里objectIDNSManagedObjectID实例。

回答by Ben Gottlieb

You might want to look at -[NSManagedObject objectID]and -[NSManagedObjectContext objectWithID:].

您可能想查看-[NSManagedObject objectID]-[NSManagedObjectContext objectWithID:]

回答by TechZen

When you build the table you do so either with an array returned by a fetch or by the implicit array inside a NSFetchResultsController. Therefore, the object you want has the same index in the array/controller as it does in the table.

当您构建表时,您可以使用 fetch 返回的数组或NSFetchResultsController. 因此,您想要的对象在数组/控制器中的索引与它在表中的索引相同。

So, it becomes simply a matter of calling:

所以,这只是一个调用的问题:

myObject=[fetchedArray objectAtIndex:tableRowIndex];

or

或者

myObject=[myFetchedResultsController objectAtIndexPath:tableRowIndex];

This is the real genius of the UITable. It always reflects the data model precisely. You never have to translate back and forth between the table indexes and your data model indexes.

这就是 UITable 真正的天才之处。它始终精确地反映数据模型。您永远不必在表索引和数据模型索引之间来回转换。