fabian
fabian

Reputation: 5463

CoreData: How to fetch a specific object using a predicate

The situation:

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

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?

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

Upvotes: 20

Views: 22510

Answers (4)

Maciek Czarnik
Maciek Czarnik

Reputation: 6181

This is proper predicate:

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

Where objectID is NSManagedObjectID instance.

Upvotes: 10

MrMage
MrMage

Reputation: 7487

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

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:

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

Upvotes: 54

TechZen
TechZen

Reputation: 64428

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.

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.

Upvotes: 2

Ben Gottlieb
Ben Gottlieb

Reputation: 85522

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

Upvotes: 3

Related Questions