Jaco Griesel
Jaco Griesel

Reputation: 375

iOS Core Data: Convert result of fetch request to an array

I'm trying to put the results of a fetch request into an array. My code:

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext
    let fetchRequest = NSFetchRequest(entityName: "CLIENTS")
    var mobClients = [NSManagedObject]()
    var arrayAllPhoneNumbers = [String]()

    do {
        let results = try managedContext.executeFetchRequest(fetchRequest)
        mobClients = results as! [NSManagedObject]

        for clientPhoneNumber in mobClients {

            let myClientPhoneNumber = clientPhoneNumber.valueForKey("clientsMobilePhoneNumber") as! String
            print(myClientPhoneNumber)
            //The numbers print out just fine, one below the other
            //
            //Now the results need to go into the array I've declared above ---> arrayAllPhoneNumbers

            messageVC.recipients = arrayAllPhoneNumbers // Optionally add some tel numbers

        }

    } catch
        let error as NSError {
            print("Could not fetch \(error), \(error.userInfo)")
    }

As illustrated, all the phone numbers needs to be captured in an array. How do I accomplish that?

Upvotes: 4

Views: 6276

Answers (3)

Sébastien REMY
Sébastien REMY

Reputation: 2470

Swift 5 : flatMap is deprecated, use compactMap

let request = NSFetchRequest(entityName: "CLIENTS")
let results = (try? managedContext.executeFetchRequest(request)) as? [NSManagedObject] ?? []

let numbers = compactMap { $0.valueForKey("clientsMobilePhoneNumber" as? String }

Upvotes: 0

Eendje
Eendje

Reputation: 8883

let request = NSFetchRequest(entityName: "CLIENTS")
let results = (try? managedContext.executeFetchRequest(request)) as? [NSManagedObject] ?? []

let numbers = results.flatMap { $0.valueForKey("clientsMobilePhoneNumber" as? String }

numbers is now an array of your phone numbers.

But like thefredelement said, it's better to subclass it so you can just cast it to that subclass and access the phone numbers directly.

Upvotes: 1

paulvs
paulvs

Reputation: 12053

Instead of your for-loop and the code inside it, use this:

arrayAllPhoneNumbers = mobClients.map({ clientPhoneNumber in
    clientPhoneNumber.valueForKey("clientsMobilePhoneNumber") as! String
})
messageVC.recipients = arrayAllPhoneNumbers

Upvotes: 4

Related Questions