我试图从我的Viewcontroller创建一个数组,使其等于我的核心数据已保存的对象。我正在使用核心数据,并创建了一个名为Pokemon的实体,该实体具有3个属性名称 id 生成。在应用程序委托中,我使用以下函数从API中获取Pokemon。这是我解析数据并保存上下文的操作:

 typealias DownloadCompleted = () -> ()
 var pokemonId: Int16 = 0

func fetchPokemon(url: String, completed: @escaping DownloadCompleted) {
    let context = coreData.persistentContainer.viewContext

    let url = URLRequest(url: URL(string: url)!)

    let task = URLSession.shared.dataTask(with: url) { (data, repsonse, error) in
        if error != nil {
            print(error!)
        }

        do {

            let jsonResult = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSDictionary
            let jsonArray = jsonResult.value(forKey: "results") as! [[String: Any]]
            for pokemonData in jsonArray {
                self.pokemonId += 1

                if self.pokemonId > 721 {

                    self.coreData.saveContext()
                    return
                }

                guard let name = pokemonData["name"] as? String else {
                    return
                }

                let pokemon = Pokemon(context: context)
                pokemon.name = name
                pokemon.id = self.pokemonId
                print("Name: \(pokemon.name) Id:\(self.pokemonId)")

                if self.pokemonId <= 151 {
                    pokemon.generation = 1
                } else if self.pokemonId <= 251 {
                    pokemon.generation = 2
                }  else if self.pokemonId <= 386 {
                    pokemon.generation = 3
                } else if self.pokemonId <= 493 {
                    pokemon.generation = 4
                } else if self.pokemonId <= 649 {
                    pokemon.generation = 5
                } else if self.pokemonId <= 721 {
                    pokemon.generation = 6
                }

            }



            guard let nextURL = jsonResult.value(forKey: "next") as? String else {
                self.coreData.saveContext()
                return
            }

            DispatchQueue.main.async {
                self.fetchPokemon(url: nextURL, completed: {
                    self.coreData.saveContext()
                })
                completed()
            }

        } catch let err {
            print(err.localizedDescription)
        }



    }
    task.resume()

}

这就是我在appDelegate中称呼它的方式。真的不知道在fetchPokemon中间该做什么或如何在另一个视图控制器中调用它。所以我将其留为空白,不确定是否与我遇到的问题有关。
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    let context = self.coreData.persistentContainer.viewContext
    let pokemonListVC = self.window?.rootViewController as! PokemonListVC
    pokemonListVC.context = context
    fetchPokemon(url: pokemonAPI) {

    }
    return true
}

我正在应用商店中使用此SQL-Light只读应用。我检查了数据,所有721宠物小精灵都在保存。现在,我不知道如何使我的视图控制器中的数组等于保存的所有721 Pokemon。我将此代码添加到我的viewController中。
class PokemonListVC: UIViewController {

  weak var context: NSManagedObjectContext! {
      didSet {
        return pokemon = Pokemon(context: context)
      }
  }
  var pokemon: Pokemon? = nil
  lazy var pokemons = [Pokemon]()
  override func viewDidLoad() {
      super.viewDidLoad()
      loadData()
  }

  func loadData() {
    pokemons = pokemon!.loadPokemon(generation: 1, context: context)
  }
}

我已经创建了我的Pokemon实体的扩展,并添加了一个功能loadPokemon,它可以按代过滤Pokemon。这是代码。
extension Pokemon {

func loadPokemon(generation: Int16 = 0, context: NSManagedObjectContext) -> [Pokemon] {
    let request: NSFetchRequest<Pokemon> = Pokemon.fetchRequest()
        request.predicate = NSPredicate(format: "generation = %@", generation)
        request.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
        do {
            let pokemons = try context.fetch(request)
            print("My Pokemon count: \(pokemons.count)")
            return pokemons
        } catch let err {
            print(err.localizedDescription)
        }
    return []
}

}

当我在ViewController中调用loadData时,它崩溃了。数组计数为0,英雄扩展中的数组计数也为0。所以我不怎么使我的数组等于从coreData保存的Pokemon。

非常感谢您提供的任何帮助。 :)

这是我的deleteRecords代码,它也在我的appDelegate中。应用启动时,这将删除所有记录。我在fetchPokemons之前的didFinishLaunchingWithOption函数的开头就调用了此方法。
func deleteRecords() {
    let context = coreData.persistentContainer.viewContext
    let pokemonRequest: NSFetchRequest<Pokemon> = Pokemon.fetchRequest()

    var deleteRequest: NSBatchDeleteRequest
    var deleteResults: NSPersistentStoreResult

    do {
        deleteRequest = NSBatchDeleteRequest(fetchRequest: pokemonRequest as! NSFetchRequest<NSFetchRequestResult>)
        deleteResults = try context.execute(deleteRequest)
    } catch let err {
        print(err.localizedDescription)
    }

}

最佳答案

正如您所说的那样,您可以确保所有的pockemon记录都正确地存储在coredata中,您只需提供获取请求就可以从代码数据中获取记录。我已经创建了用于联系人存储的演示,并且可以通过此获取请求获取所有联系人,您可以在要获取所有记录的ViewController中尝试此代码。

 let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let managedContext = appDelegate.persistentContainer.viewContext
    let fetchRequest = NSFetchRequest<NSManagedObject> (entityName: "Pokemon")

    do {
        arrPockemon = try managedContext.fetch(fetchRequest)

    }catch let error as NSError {
        showAlert(string: error.localizedDescription)
    }

尝试先获取所有记录,如果获取全部,则尝试过滤扩展名和全部。希望对您有帮助。你可以从这里学习https://code.tutsplus.com/tutorials/core-data-and-swift-core-data-stack--cms-25065

在userDefault上保存标志。
 //check for first time when app is installed first time(first time flag is not present so)
    let userDefault = UserDefaults.standard.dictionaryRepresentation()
    if userDefault.keys.contains("isDataAvailable") {
        //key is availebe so check it
        if userDefault["isDataAvailable"] as! String == "1"{
            //no need to call server for data
        }else{
            //fetch data from server
            // once you get data from server make isDataAvailable flage as 1
            UserDefaults.standard.setValue("1", forKey: "isDataAvailable")
            UserDefaults.standard.synchronize()
        }
    }
    else{
        //flag is not avalable so call server for data
        // once you get data from server make isDataAvailable flage as 1
        UserDefaults.standard.setValue("1", forKey: "isDataAvailable")
        UserDefaults.standard.synchronize()
    }

10-08 16:59