2017-04-08 47 views
2

我想從我的Viewcontroller創建一個數組,等於我的核心數據已保存的對象。我使用的核心數據,並創建了一個名爲實體口袋妖怪其中有3個屬性ID。在應用程序代理中,我使用以下函數從此API獲取Pokemon。這是我做的解析數據和保存上下文:從AppDelegate載入已保存的上下文到另一個ViewController

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口袋妖怪保存。我將這段代碼添加到我的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) 
    } 
} 

我已經建立了我口袋妖怪實體的擴展,增加了一個功能loadPokemon通過一代過濾口袋妖怪。這是代碼。

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保存的口袋妖怪。

非常感謝您提供的任何幫助。 :)

這是我的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) 
    } 

} 

回答

0

正如你說你有確保所有的pockemon記錄被正確地存儲在您的coredata你可以簡單地從你的codedata通過提供獲取請求提取記錄。我已經創建了聯繫人存儲的演示,並且可以通過此獲取請求獲取所有聯繫人,您可以在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() 
    } 
+0

我在應用程序委託中沒有核心數據堆棧。我將它從應用程序委託移動到我創建的單獨文件。 –

+0

好吧,那麼你可以試試這個,讓context = coreData.persistentContainer.viewContext並嘗試獲取記錄。 – Pankaj

+0

好吧,當我註釋掉我的deleteRecords()方法時,它開始工作,但是當我取消註釋時,數組爲0. –

相關問題