Kapil_A
Kapil_A

Reputation: 135

How to get unique objects from NSFetchedResultsController?

I have an entity Contact which has duplicate contact object. Eg :

|---------------------|------------------|---------------|
|     Name            |    Index Value   |   Number      |
|---------------------|------------------|---------------|
|  Daniel Higgins     |         4        |    12345      |
|---------------------|------------------|---------------|
|  Daniel Higgins     |         4        |    123456789  |

Now here i am fetching the contact using NSFetchedResultsController and using it for UITableviewController.

Here i want to show only one entry for name Daniel Higgins. How can i filter out the unique objects from NSFetchedResultsController based on idexvalue.

Upvotes: 1

Views: 893

Answers (2)

FlixMa
FlixMa

Reputation: 943

You can create your request like this (where ContactResult is your generated class from core data):

    let request = NSFetchRequest<ContactResult>(entityName: "contacts")
    request.propertiesToFetch = ["name"]    // an array of properties between which should be distinguished
    request.returnsDistinctResults = true   // dont do duplicates

This way it is not possible to get other properties like number as well, otherwise they would be distinct again and Daniel Higgins will pop up twice again. If thats actually what you want (get name and at least one number (don't care which)), then you could also use group by:

    let request = NSFetchRequest<ContactResult>(entityName: "contacts")
    request.propertiesToGroupBy = ["name"]    // an array of properties between which should be grouped if there are duplicates

Warning: Which number gets chosen if there are multiple, may not be consistent!

However, then you could directly fetch the results as suggested by Mehul Parmar:

    context.fetch(request)

or instead use a Controller as you suggested and therefore make use of its delegate and be notified of upcoming changes:

    let controller = NSFetchedResultsController(
        fetchRequest: request,
        managedObjectContext: context,
        sectionNameKeyPath: nil,    // just for demonstration: nil = dont split into section
        cacheName: nil              // and nil = dont cache
    )

Upvotes: 1

Mehul Parmar
Mehul Parmar

Reputation: 3699

When you create a fetchResultsController request object, apply a predicate to it to filter out entries based on the name you want.

Then, when you fetch the objects using context.fetch(request), if there are multiple entries, you can simply use the first one.

Upvotes: 0

Related Questions