S.ork
S.ork

Reputation: 229

Core Data fetch entities with only unique attributes

I have an Entity "Person" with following attributes:

-name
-surname
-age

I created numbers of objects:

(Ben,    Black,    18)
(John,  Smith,    19)
(Ivan,   Borzov,   18)
(Den,   Balan,     20)
(Kent,  Broman,  20)

How to receive array or any other way to build a table with only unique ages [18,19,20]

Please provide answer in Swift.

P.S. Of course I can fetch all objects, and search for unique manually, but I hope for better solution)

Thank you!

Upvotes: 5

Views: 3573

Answers (3)

Ahmed Onawale
Ahmed Onawale

Reputation: 4050

You can both propertiesToFetch and returnsDistinctResults properties of NSFetchRequest to get distinct result of ages across all entities.

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSFetchRequest_Class/#//apple_ref/occ/instp/NSFetchRequest/propertiesToFetch

let fetchRequest = NSFetchRequest(entityName: "Person")
fetchRequest.resultType = .DictionaryResultType
fetchRequest.propertiesToFetch = ["age"]
fetchRequest.returnsDistinctResults = true
let result = try! managedObjectContext.executeFetchRequest(fetchRequest)

Upvotes: 7

S.ork
S.ork

Reputation: 229

Thank you for your answer, but this is exactly what I call "manually search" I made it even little bit simple:

let fetchRequest = NSFetchRequest(entityName: "Person")
do {
  let results = try managedContext.executeFetchRequest(fetchRequest)
  persons = results as! [Person]
} catch let error as NSError {
  print("Could not fetch \(error), \(error.userInfo)")
}

var temporaryArray = [String]()
for person in persons {
  if let age = person.age {
    temporaryArray.append(age)
  }
}
ages = Array(Set(temporaryArray))

Upvotes: 0

Jigar Tarsariya
Jigar Tarsariya

Reputation: 3247

You can retrieve ages like below code, Call this in view did load,

var getAllLogObj = [NSManagedObject]()
var allLogsArray : NSMutableArray = NSMutableArray()

func getAllLogs()
{
    let appDelegate =
    UIApplication.sharedApplication().delegate as! AppDelegate

    let managedContext = appDelegate.managedObjectContext

    let fetchRequest = NSFetchRequest(entityName:"Person")

    var fetchedResults = [NSManagedObject]()

    let _ : NSError! = nil
    do {
        fetchedResults = try managedContext.executeFetchRequest(fetchRequest) as! [NSManagedObject]
        getAllLogObj = fetchedResults

    } catch {
        print("Fetching error : \(error)")
    }

    if(getAllLogObj.count > 0)
    {
        self.allLogsArray.removeAllObjects()
        self.allLogsArray = NSMutableArray()

        for(var i : Int = 0; i < getAllLogObj.count; i++)
        {
            let ageString = getAllLogObj[i].valueForKey("age") as? NSString
            self.allLogsArray.addObject(ageString)
        }

    }
    self.tblComplaintList.reloadData()
}

Its working fine at my end. Hope this will help to you also.

Upvotes: 0

Related Questions