核心数据需要时间插入记录与获取实体&设置为关系的记录。

问题描述 投票:0回答:1

我有2个实体:Components &SurveyReadingWeb,它们是一对多的关系。我已经将Components数据保存在核心数据库中,但在保存SurveyReadingWeb时--在一个for循环中--我必须通过传递components id和设置surveyreadings isComponentexists关系来获取Components数据实体,就像下面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
}
ios swift performance relationship
1个回答
0
投票

如果你添加了一个新功能,你可以大大减少时间。NSCache 实例来缓存 compID:Components 键值对。

getCompNameFromID 检查是否 compID 存在于缓存中。如果存在,则从缓存中获取值(非常快),如果不存在,则从缓存中获取记录,并将其保存到 compID 的缓存中。

并使用方便的 SurveyReadingWeb(context: 初始化器,以摆脱所有丑陋的问号,然而性能上的好处相当小。

© www.soinside.com 2019 - 2024. All rights reserved.