简体   繁体   中英

adding data to CoreData takes lot time

// code to add core data. have 2000 contacts to add. but adding 2000 data takes 45 secs.

func addData(contacts: [CNContact]) {
    for data in contacts {
         let context = appDelegate.persistentContainer.viewContext
        let entity = NSEntityDescription.entity(forEntityName: entityName, in: context)
        let newUser = NSManagedObject(entity: entity!, insertInto: context)
        newUser.setValue(data.identifier, forKey: "contactIdentifier")
        newUser.setValue(data.familyName, forKey: "finalName")
        newUser.setValue(data.givenName, forKey: "givenName")
        newUser.setValue(data.phoneNumbers.first?.value.value(forKey: "stringValue") as? String ?? "", forKey: "phoneNumber")
        do {
            try context.save()
        } catch {
            UIUtility.showErrorAlert("", message: Constants.errorMessage)
        }
    }

}

First move this line to before the loop since you only need to do it once

let context = appDelegate.persistentContainer.viewContext

Then replace the next two lines with

let newUser = NSEntityDescription.insertNewObject(forEntityName entityName, into: context)

So the start of the function should look like this

let context = appDelegate.persistentContainer.viewContext
for data in contacts {
    let newUser = NSEntityDescription.insertNewObject(forEntityName entityName, into: context)
    //...

Creating context and entity once (a bit more efficient) and saving the context once (much more efficient) is certainly faster.

func addData(contacts: [CNContact]) {
    let context = appDelegate.persistentContainer.viewContext
    let entity = NSEntityDescription.entity(forEntityName: entityName, in: context)!
    for data in contacts {
        let newUser = NSManagedObject(entity: entity, insertInto: context)
        newUser.setValue(data.identifier, forKey: "contactIdentifier")
        newUser.setValue(data.familyName, forKey: "finalName")
        newUser.setValue(data.givenName, forKey: "givenName")
        newUser.setValue(data.phoneNumbers.first?.value.value(forKey: "stringValue") as? String ?? "", forKey: "phoneNumber")
    }
    do {
       try context.save()
    } catch {
       UIUtility.showErrorAlert("", message: Constants.errorMessage)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM