获取单个核心数据元素并组合成单个数组

fetch single core data elements and combine into single array

我的 swift 下面的代码将 3 个名字保存到核心数据。然后在 func joke 中,它获取数据并将其转换为调试区域中的 array.The 问题,而不是列出 3 个名称,如 [kim、Hailey、jessica]。它在每一行列出它们,因此它们不会分组在一个数组中。所以我想要所有 3 个名称,例如 [name1,name2,name3].

    import UIKit
import CoreData

class ViewController: UIViewController,UITextFieldDelegate {
@IBOutlet var labelName : UILabel!
@IBOutlet var enterT : UITextField!

let appDelegate = UIApplication.shared.delegate as! AppDelegate //Singlton instance
var context:NSManagedObjectContext!

override func viewDidLoad() {
    super.viewDidLoad()

    openDatabse()
    joke()

}
func joke() {

    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")

 do {
    let results = try context.fetch(fetchRequest)
     let  Locations = results as! [Users]

     for location in Locations {
        print("Array: ",location.username)


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

}

func openDatabse()
{
    context = appDelegate.persistentContainer.viewContext
    let entity = NSEntityDescription.entity(forEntityName: "Users", in: context)
    let newUser = NSManagedObject(entity: entity!, insertInto: context)
    let newUser2 = NSManagedObject(entity: entity!, insertInto: context)
    let newUser3 = NSManagedObject(entity: entity!, insertInto: context)
    saveData(UserDBObj: newUser, UserDBObj2: newUser2, UserDBObj3: newUser3)

}

func saveData(UserDBObj:NSManagedObject,UserDBObj2:NSManagedObject,UserDBObj3:NSManagedObject)
{
    UserDBObj.setValue("kim kardashian", forKey: "username")
    UserDBObj2.setValue("jessica biel", forKey: "username")
    UserDBObj3.setValue("Hailey Rienhart", forKey: "username")




    print("Storing Data..")
    do {
        try context.save()
    } catch {
        print("Storing data Failed")
    }

    fetchData()
}

func fetchData()
{
    print("Fetching Data..")
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
    request.returnsObjectsAsFaults = false
    do {
        let result = try context.fetch(request)
        for data in result as! [NSManagedObject] {
            let userName = data.value(forKey: "username") as! String

            print("User Name is : "+userName)
        }
    } catch {
        print("Fetching data Failed")
    }
}}

CoreData 获取数据时,将您的 managed object 转换为您的模型 class 数组。

附上代码供您参考。

   do{
        if let userData = try managedContext?.fetch(fetchRequest) as? [Users]{
               // use this userData for your result and update ui accordingly    
       }

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

获取数据后,获取一个字符串数组并将您的用户名附加到该数组中。参考下面的代码

var nameArray = [String]()
for location in Locations {
         print("Array: ",location.username)
         nameArray.append(location.username)  
     }

首先使用特定的获取请求获取 Users 条记录。

如果你想要一个字符串数组([String])map记录到他们的用户名

func joke() {
    let fetchRequest = NSFetchRequest<Users>(entityName: "Users")
    do {
        let result = try context.fetch(fetchRequest)
        let nameArray = result.map{[=10=].username}
        print(nameArray)
    } catch {
       print("Could not fetch \(error) ")
    }
}

但是如果你想要单个字符串以逗号分隔 join 数组

let nameString = result.map{[=11=].username}.joined(separator: ", ")
print(nameString)