2016-08-17 8 views
0

こんにちは、私は世界中の都市、つまり127960都市のデータを持っています。このデータをアプリケーションデータベースに挿入しようとしています。それは約20分かかります。コアデータがデータベースにデータを挿入するのに時間がかかります

//Here is code 

    private func FetchCountryList(){ 

     var parameters = [String:AnyObject]() 

     if let rDate = Country.GetLatestDate() as NSNumber?{ 
      parameters[RECORDED_DATE] = rDate.integerValue 
     } 

     WSRequest.SendRequest(WSMethod.POST, pramrDisc: parameters, paramsString:nil, operation: WSOperation.FetchCountryList, completionHandler: {response in 

      if let parsedObject = response.parsedObject as? [String:AnyObject]{ 

       if let countries = parsedObject[OBJECT1]?[COUNTRIES] as? [[String:AnyObject]]{ 

        let managedContext = CoreDataStack.sharedStack().backgroundContext 

        managedContext.performBlock({ 

         for country in countries { 
          AddCountryInManagedObjectContext(country) 
         } 

         managedContext.saveContext() 
         self.completedDataBurning() 

        }) 
       } 
      } 
     }) 
    } 

class func AddCountryInManagedObjectContext(user:[String:AnyObject]) { 

    if let countryId = user[COUNTRY_ID] as? Int{ 

     let backgroundContext = CoreDataStack.sharedStack().backgroundContext 
     backgroundContext.performBlockAndWait({ 

      let newItem = DatabaseManager.CreateOrUpdateItemFor(backgroundContext,entity: TABLE_COUNTRY, parameter: "countryId", value: countryId) as! Country 

      newItem.countryId = countryId 

      if let countryName = user[COUNTRY_NAME] as? String{ 
       newItem.countryName = countryName.capitalizedString 
      } 

      if let currency = user[CURRENCY] as? String{ 
       newItem.currency = currency.uppercaseString 
      } 

      if let currencyCode = user[CURRENCY_CODE] as? Int{ 
       newItem.currencyCode = currencyCode 
      } 

      if let currencySymbol = user[CURRENCY_SYMBOL] as? String{ 
       newItem.currencySymbol = currencySymbol 
      } 

      if let recordedBy = user[RECORDED_BY] as? String{ 
       newItem.recordedBy = recordedBy.capitalizedString 
      } 

      if let recordedDate = user[RECORDED_DATE] as? Double{ 
       newItem.recordedDate = recordedDate 
      } 

      if let status = user[STATUS] as? String{ 
       if status == "D"{ 
        DeleteRecord(backgroundContext,entityName: TABLE_COUNTRY, columnName: "countryId", recordId: "\(countryId)") 
       } 
      } 

     }) 

    } 
} 

class func DeleteRecord(managedContext:NSManagedObjectContext,entityName:String,columnName:String,recordId:String) { 


    managedContext.performBlockAndWait({ 

     //2 
     let fetchRequest = NSFetchRequest(entityName:entityName) 
     fetchRequest.includesPropertyValues = false 

     let predicateFormat = "\(columnName) = \(recordId)" 

     let resultPredicate = NSPredicate(format: predicateFormat) 
     fetchRequest.predicate = resultPredicate 

     //3 
     //var error: NSError? 

     do { 

      if let results = try managedContext.executeFetchRequest(fetchRequest) as? [NSManagedObject]{ 

       for result in results{ 
        managedContext.deleteObject(result) 
       } 
      } 

      try managedContext.save() 

     } catch let error as NSError { 
      print(error) 
     } 
    }) 
} 
    //Core data stack 

     import CoreData 

     let coreDataStack = CoreDataStack() 

     class CoreDataStack { 
     class func sharedStack() -> CoreDataStack{ 
      return coreDataStack 
     } 

     // MARK: - Core Data stack 

     lazy var applicationDocumentsDirectory: NSURL = { 
      // The directory the application uses to store the Core Data store file. This code uses a directory named "in.appstute.TripOrb" in the application's documents Application Support directory. 
      let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) 
      return urls[urls.count-1] 
     }() 

     lazy var managedObjectModel: NSManagedObjectModel = { 
      // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. 
      let modelURL = NSBundle.mainBundle().URLForResource("TripOrb", withExtension: "momd")! 
      return NSManagedObjectModel(contentsOfURL: modelURL)! 
     }() 

     lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { 
      // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. 
      // Create the coordinator and store 
      let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) 
      let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") 
      var failureReason = "There was an error creating or loading the application's saved data." 
      do { 
       try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) 
      } catch { 
       // Report any error we got. 
       var dict = [String: AnyObject]() 
       dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" 
       dict[NSLocalizedFailureReasonErrorKey] = failureReason 

       dict[NSUnderlyingErrorKey] = error as NSError 
       let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) 
       // Replace this with code to handle the error appropriately. 
       // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
       NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") 
       abort() 
      } 

      return coordinator 
     }() 

     lazy var context: NSManagedObjectContext = { 
      // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. 
      let coordinator = self.persistentStoreCoordinator 
      var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) 
      managedObjectContext.persistentStoreCoordinator = coordinator 
      return managedObjectContext 
     }() 

     lazy var backgroundContext: NSManagedObjectContext = { 
      // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. 
      let coordinator = self.persistentStoreCoordinator 
      var managedObjectContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType) 
    //  managedObjectContext.persistentStoreCoordinator = coordinator 
      managedObjectContext.parentContext = self.context 

      return managedObjectContext 
     }() 

     // MARK: - Core Data Saving support 

     func saveContext() { 
      if context.hasChanges { 
       do { 
        try context.save() 
       } catch { 
        // Replace this implementation with code to handle the error appropriately. 
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
        let nserror = error as NSError 
        NSLog("Unresolved error \(nserror), \(nserror.userInfo)") 
        abort() 
       } 
      } 
     } 

     func saveBackgroundContext() { 
      if backgroundContext.hasChanges { 
       do { 
        try backgroundContext.save() 
       } catch { 
        // Replace this implementation with code to handle the error appropriately. 
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
        let nserror = error as NSError 
        NSLog("Unresolved error \(nserror), \(nserror.userInfo)") 
        abort() 
       } 
      } 
     } 
    } 

    extension NSManagedObjectContext { 
     func saveContext() { 
      if self.hasChanges { 
       do { 
        try self.save() 
       } catch { 
        // Replace this implementation with code to handle the error appropriately. 
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
        let nserror = error as NSError 
        NSLog("Unresolved error \(nserror), \(nserror.userInfo)") 
        abort() 
       } 
      } 
     } 
    } 
+1

楽器を使用して、コアデータに何をするよう求めていますか?データ読み込みに関するその他の回答をお読みください。 – Wain

+0

** ** sqlite **とプログラマ間の中間層であり、処理する複数のスレッドをサポートしていないため、大規模なデータ処理には** ** sqlite **を使用してください。 – vaibhav

+0

@vaibhavバッチインサート状況?シーケンシャルバッチインサートは明らかな解決策のようです。 – Voo

答えて

0

「コアデータプログラミングガイド」のEfficiently Importing Dataの章を参照してください。

最適値と思われるバッチサイズ1000で試してください。

+0

そのリンクでその章を見つけることができれば、正確にどこを見つけるか説明できますか?その名前のセクションがあったことは分かっていましたが、最近は見つかりませんでした。 –

関連する問題