Базовым данным требуется время для вставки записей с извлечением объекта и установки как отношения - PullRequest
0 голосов
/ 29 мая 2020

У меня есть 2 объекта: Components и SurveyReadingWeb, которые связаны отношениями «один ко многим». Я сохранил данные компонентов в базе данных основных данных; но при сохранении SurveyReadingWeb - для l oop - мне нужно получить объект данных Components, передав идентификатор компонента и установив отношение SurveyReadingWeb isComponentexists, как в приведенном ниже коде для 8000 записей. Этот процесс занимает слишком много времени, почти 7 минут. Как мне сократить время?

for item in items {
            autoIncrementId = autoIncrementId + 1
            print("reading items parsed:- \(item.SurveyReadingId), \(autoIncrementId)")

            let reading : SurveyReadingWeb? = NSEntityDescription.insertNewObject(forEntityName: Constants.EntityNames.kSURVEYREADINGWEB, into: self.managedContext) as? SurveyReadingWeb
            reading?.surveyId1 = Int32(autoIncrementId)
            reading?.surveyId = Int32(item.SurveyId) ?? 0
            reading?.readingData = item.CH4
            reading?.surveyDateTime = item.SurveyReadingDateTime
            reading?.latitude = item.Latitude
            reading?.longitude = item.Longitude
            reading?.serialNumber = item.SerialNumber
            reading?.descriptionText = item.Description
            reading?.componentName = item.Description
            reading?.componentId = Int32(item.ComponentId) ?? 0
            reading?.readingTypeId = Int32(item.ReadingTypeID) ?? 0
            reading?.readingTypeDetails = item.ReadingTypeDetails

            reading?.currentLatitude = item.CurrentLatitude
            reading?.currentLongitude = item.CurrentLongitude
            reading?.hdop = item.HDOP
            reading?.vdop = item.VDOP
            reading?.componentDistance = item.ComponentDistance
            reading?.facilityId = Int32(item.ProjectId) ?? 0
            reading?.posted = 1
            reading?.readyToSync = 1

            reading?.isComponentExists = DatabaseManager.sharedManager.getCompNameFromID(compID: Int32(item.ComponentId) ?? 0)
        }
        saveContext()


func getCompNameFromID(compID : Int32) -> Components? {
    var component : Components? = nil
    let fetchRequest : NSFetchRequest<Components> = Components.fetchRequest()
    fetchRequest.predicate = NSPredicate(format: "componentId == %ld", compID)

    do {
        let searchResults = try managedContext.fetch(fetchRequest)
        component =  (searchResults.first) ?? nil
    } catch {
    }
    return component ?? nil
}

1 Ответ

0 голосов
/ 29 мая 2020

Вы можете значительно сократить время, если добавите экземпляр NSCache в кешируемые пары ключ-значение compID:Components.

В getCompNameFromID проверьте, существует ли compID в кеше. Если да, получите значение из кеша (очень быстро), если нет, выберите запись и сохраните ее для compID в кеше.

И используйте удобный инициализатор SurveyReadingWeb(context:, чтобы избавиться от всех уродливые вопросительные знаки, однако прирост производительности весьма незначителен.

...