iOS Core Data: Convert result of fetch request to

2019-05-30 08:14发布

问题:

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?

回答1:

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


回答2:

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.



标签: swift xcode7