Search code examples
swiftxcode7

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?


Solution

  • 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