是否可以快速从CoreData中获取数组?

时间:2019-06-03 17:08:46

标签: ios arrays swift core-data

我已经在CoreData中存储了一些字符串(例如人名)。现在,我想将这些名称加载到数组中。

func loadData() -> Array<String> {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext

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

    request.returnsObjectsAsFaults = false




    var test = ""
    var DataArray = [String]()

    do {
       let results = try context.fetch(request)


        if results.count > 0 {

            for result in results as! [NSManagedObject] {

                if let firstusername = result.value(forKey: "username") as? String {
                    test = firstusername
                }
                testArray.append(contentsOf: test)
            }

        }
    } catch  {
        print("Roor")
    }
            print(type(of: test))

            return testArray

}

我总是收到此错误消息:实例方法'append(contentsOf :)'要求类型'String'和'String.Element'(aka'Character')是等效的

1 个答案:

答案 0 :(得分:1)

append(contentsOf:需要一系列项目,您只需要使用append(,然后将附加行移到if let正文中

if let firstusername = result.value(forKey: "username") as? String {
   testArray.append(firstusername)
}

或者如果您没有名称则要附加一个空字符串

testArray.append((result.value(forKey: "username") as? String) ?? "")

尽管如此,您的方法包含很多冗余代码,这已经足够

func loadData() throws -> Array<String> {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext    
    let request = NSFetchRequest<Users>(entityName: "Users")    
    request.returnsObjectsAsFaults = false        
    let results = try context.fetch(request)
    return results.compactMap{ $0.username } 
}

它返回名称数组或移交潜在错误。