ios - 核心数据将数据插入数据库需要很长时间

标签 ios swift multithreading performance core-data

您好,我有全局城市的数据,即 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()
                }
            }
        }
    }

最佳答案

查看 Efficiently Importing Data核心数据编程指南中的相关章节。

尝试使用 1000 的批量大小,这似乎是最佳值。

关于ios - 核心数据将数据插入数据库需要很长时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38989644/

相关文章:

iphone - 是否可以使用iPod Touch 4开发可同时运行并发布给iPhone和iPod Touch的iOS应用程序?

ios - GLKViewController 中带有 glTexImage2D 的 EXC_BAD_ACCESS

ios - 在 Swift 闭包的闭包内部使用 unowned

ios - 如何使用导航 Controller 调用 View Controller

ios - UIViewController 在纵向模式下空白,但 subview 在横向模式下可见?

c++ - std::memory_order_relaxed 是否足以检查 "Availability"?

ios - (Siri) 创建自己的 resolve 方法

ios - 对字符串数组进行排序并忽略大小写

ruby - Ruby 中的限时计算

java - 多线程环境中的快速 MultiMap