在CoreData中添加数据需要花费大量时间

时间:2017-03-28 21:40:36

标签: ios swift core-data

我在 CoreData 中有一个模型如下所示: enter image description here

添加的结构看起来像树,例如:

let context = CoreDataManager.instance.getContext()
for i in stride(from: 0, to: (RegionNames.count)!, by: 1){    
    let regions = Regions(context: context)
    regions.name = RegionName
    for j in stride(from: 0, to: (DistrictNames.count)!, by: 1){
        let districts = Districts(context: context)
        districts.name = DistName
        regions.addToRegToDist(districts)
        for k in stride(from: 0, to: (StreetNames.count)!, by: 1){
            let streets = Streets(context: context)
            streets.name = StreetName
            districts.addToDistToStr(streeets)
            for k in stride(from: 0, to: (AddressNames.count)!, by: 1){
                let addresses = Addresses(context: context)
                addresses.name = AddressName
                //+few attributes
                streets.addToStrToAddresses(addresses)
                districts.addToDistToAddresses(addresses)
                regions.addToRegToAddresses(addresses)
            }
        }
    }
}
CoreDataManager.instance.saveContext(context: context)

Regions类和其他实体如下所示:

public class Regions: NSManagedObject {
    convenience init(context:NSManagedObjectContext) {
        let entity = NSEntityDescription.entity(forEntityName: "Regions", in: context)

        self.init(entity: entity!, insertInto: context)
    }
} 

完全可行,但需要花费很长时间。我在UI中只有静态活动指示器。没有什么变化。我觉得有些事情不对,但我不知道如何改变它。

修改

我使用此设置例如:

RegionNames.count == 1
DistrictNames.count == 10
StreetNames.count ~ 10-15 //in each district
AddressNames.count ~ 500 //items in each district or about 10-50 items in each streets.

我在Android上拥有相同的应用程序,节省时间最多为15秒。但是,这个应用大约8分钟,这是绝对不能接受的。

具有获取和保存上下文的CoreDataManager类(iOS> 10.0):

    class CoreDataManager {

    // Singleton
    static let instance = CoreDataManager()

    private init() {}

    @available(iOS 10.0, *)
    lazy var persistentContainer: NSPersistentContainer = {

        let container = NSPersistentContainer(name: "Addresses")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error {

                fatalError("Unresolved error \(error)")
            }
        })
        return container
    }()

    func getContext () -> NSManagedObjectContext {
        var context: NSManagedObjectContext?

        if #available(iOS 10.0, *) {
            context = persistentContainer.viewContext
        } 
    }

    func saveContext(context: NSManagedObjectContext){
        if (context.hasChanges){
            do {
                try context.save()
                //print("saved!")
            } catch let error as NSError  {
                print("Could not save \(error), \(error.userInfo)")
            } catch {

            }
        }
    }
}

0 个答案:

没有答案