ios 从核心数据中检索[String]类型的Transformable

ezykj2lf  于 2023-11-19  发布在  iOS
关注(0)|答案(1)|浏览(92)

“我的核心数据”属性设置为可转换,“模型”检查器中的自定义类设置为[String]
我可以像这样保存数据:

func saveResultsObjects(results: [String]) {
    let entity   = NSEntityDescription.entity(forEntityName: "ResultsObjects", in: context)
    let result = NSManagedObject(entity: entity!, insertInto: privateContext)
        
    result.setValue(results, forKey: "results")
        
    do {
        try privateContext.save()
        print("Success Saving In CoreData!")
    } catch {
        print("Failed Saving In CoreData!")
    }
}

字符串
试着用这种方式来检索:

func getResultsObjects() -> [String] {
        var retrievedResults = [String]()
        
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ResultsObjects")
        let result = try? privateContext.fetch(fetchRequest)
        for data in result as! [NSManagedObject] {
            
            let results = data.value(forKey: "results") as? [String]
            
//            retrievedResults.append(results)
            retrievedResults[0] = "\(String(describing: results))"
        }
        return retrievedResults
    }


但是当尝试在索引超出范围的retrievedResults[0]上检索时会崩溃
我只保存了HTML数据中的[String]。我做错了什么?

mklgxw1f

mklgxw1f1#

解决方法是创建一个空的String数组,并在不指定索引的情况下将获取的数据追加到该数组

func getResultsObjects() -> [String]? {
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "ResultsObjects")
    request.returnsObjectsAsFaults = false
    
    var retrievedResults = [String]()
    
    do {
        let result = try privateContext.fetch(request)
        
        for data in result as! [NSManagedObject] {
            
            guard let results = data.value(forKey: "results") as? [String] else { return nil }
            retrievedResults = results
            
        }
        return retrievedResults
        
    } catch {
        print("Getting Data failed!")
    }
    return nil
}

字符串

相关问题