реализация основных данных с неповторяющимся кодом для большого проекта - PullRequest
0 голосов
/ 07 июня 2018

У меня есть проект, в котором я использую его из Deployment Target = 9.0, более 10 сущностей Coredata, здесь я пытаюсь сделать подход, при котором модель не вызывается из View, и у меня есть один метод, который принимает запрос на выборку и выполнениезадание.Это мой подход

AppDelegate.swift

 // MARK: - Core Data stack

lazy var applicationDocumentsDirectory: URL = {
    let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {

    let modelURL = Bundle.main.url(forResource: "CoreDB", withExtension: "momd")!
    return NSManagedObjectModel(contentsOf: modelURL)!
}()

    lazy var managedObjectContext: NSManagedObjectContext = {
    let coordinator = self.persistentStoreCoordinator
    var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
    managedObjectContext.persistentStoreCoordinator = coordinator
    return managedObjectContext
}()
  lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {

    // Create the coordinator and store
    let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
    let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("CoreDB.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 {

    }

    return coordinator
    }()
  // MARK: - Core Data stack
@available(iOS 10.0, *)
lazy var persistentContainer: NSPersistentContainer = {
    /*
     The persistent container for the application. This implementation
     creates and returns a container, having loaded 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.
     */
    let container = NSPersistentContainer(name: "CoreDB")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() 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.

            /*
             Typical reasons for an error here include:
             * The parent directory does not exist, cannot be created, or disallows writing.
             * The persistent store is not accessible, due to permissions or data protection when the device is locked.
             * The device is out of space.
             * The store could not be migrated to the current model version.
             Check the error message to determine what the actual problem was.
             */
            print("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()

// MARK: - Core Data Saving support

func saveContext () {
    if #available(iOS 10.0, *) {
    let context = persistentContainer.viewContext
    if context.hasChanges {
        do {
            try context.save()
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() 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
            fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }
    }
    else
    {
        if managedObjectContext.hasChanges {
            do {
                try managedObjectContext.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()
            }
        }
    }
}

CoredataHelper.swift

class func fetchCoreData(_ entity:String, key:String, order : Bool) -> NSArray {
    //let context: NSManagedObjectContext = appDelegate.managedObjectContext
    if #available(iOS 10.0, *) {
         let persistantContainer =  appDelegate.persistentContainer
        let privateManagedObjectContext = persistantContainer.newBackgroundContext()
        let managedObjectContext = persistantContainer.viewContext
        var arr : NSArray = []
        let request = NSFetchRequest<NSFetchRequestResult>(entityName: entity)
        let sortDescriptor = NSSortDescriptor(key: key, ascending: order)
        request.sortDescriptors = [sortDescriptor]
        do {
            guard let searchResults : NSArray = try privateManagedObjectContext.fetch(request) as NSArray else {
                print("Results were not of the expected structure")
            }
            arr = searchResults
        } catch {
            print("Error ocurred during execution: \(error)")
        }
        return arr
    }
    else
    {
    let moc = DbHelper .getContext()

    let privateMOC = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
    privateMOC.parent = moc
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entity)
    fetchRequest.returnsObjectsAsFaults = false;
    let sortDescriptor = NSSortDescriptor(key: key, ascending: order)
    fetchRequest.sortDescriptors = [sortDescriptor]
    do {
        let fetchDetails : NSArray = try moc.fetch(fetchRequest)  as NSArray
        return fetchDetails
    } catch {
        Crashlytics.sharedInstance().recordError(error)
        return []
    }
    }

}

class func saveData(_ arr : NSArray) {

    for i in 0  ..< arr.count
    {
        let dictionary = arr .object(at: i) as? NSDictionary
        let entityDescription =
            NSEntityDescription.entity(forEntityName: “1”,
                                              in: managedObjectContext)

        let req = NSFetchRequest<NSFetchRequestResult>(entityName: “1”)
        req.sortDescriptors = [NSSortDescriptor(key: "createdAt", ascending: true)]
        let localId = "\(String(describing: dictionary!["createdAt"]!))"
        let pred = NSPredicate(format:"createdAt == \(localId)")
        req.predicate = pred
        do {
            let fetchedResults = try managedObjectContext.fetch(req) as! [1]
            if fetchedResults.count > 0 {

            }     
            else
            {
                let 1DataObj = 1(entity: entityDescription!,
                                           insertInto: managedObjectContext)
                 print(dictionary)

                1DataObj.createdAt = dictionary!["createdAt"]! as! NSNumber
            }

        }
        catch {
            print("Error getting values")
        }

    }
    if managedObjectContext.hasChanges {
        do {
            try managedObjectContext.save()
        } catch let nserror as NSError {

        }
    }

}

ViewController.swift

       // Fetching 
        Array1 =  CoredataHelper .fetchCoreData("1", key:"name", order: true)
        Array2 = CoredataHelper .fetchCoreData("2", key:"hubId", order: true)
        Array3 =  CoredataHelper .fetchCoreData("3", key:"createdAt", order: true)
        Array4 =  CoredataHelper .fetchCoreData("4", key:"name", order: true)
        Array5 =  CoredataHelper .fetchCoreData("5", key:"name", order: false)
        Array6 =  CoredataHelper .fetchCoreData("6", key:"name", order: false)

       //Save response from API
       CoredataHelper .saveData(arr)

Можно ли как-нибудь улучшить это на основе передового опыта, который я хочу реализовать для iOS 9 до последней версии iOS.

...