mskw
mskw

Reputation: 10358

Core data indexing in iOS11

There seem to be new API's in iOS11 that allows CoreData indexing:

NSFetchIndexDescription and NSFetchIndexElementDescription

I tried all over the web, there seem to be no documentation from Apple or anyone using it.

I'm trying to create an index to do faster searches in CoreData.

Upvotes: 1

Views: 1176

Answers (1)

Vlad
Vlad

Reputation: 6730

I did following when setting up NSManagedObjectModel from Swift code:

import Foundation
import CoreData

class ManagedObjectModel: NSManagedObjectModel {

    override init() {
        super.init()
        entities.append(makePostEntity())
        ...
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError()
    }
}

extension ManagedObjectModel {

    private func makePostEntity() -> NSEntityDescription {

        let attributeCreatedDate = NSAttributeDescription()
        attributeCreatedDate.name = #keyPath(PostEntity.createdDate)
        attributeCreatedDate.attributeType = .dateAttributeType
        attributeCreatedDate.isOptional = false

        let attributeID = NSAttributeDescription()
        attributeID.name = #keyPath(PostEntity.id)
        attributeID.attributeType = .stringAttributeType
        attributeID.isOptional = false

        ...

        let attributeVideoURL = NSAttributeDescription()
        attributeVideoURL.name = #keyPath(PostEntity.videoURL)
        attributeVideoURL.attributeType = .URIAttributeType
        attributeVideoURL.isOptional = true

        let indexDescription1 = NSFetchIndexElementDescription(property: attributeCreatedDate, collationType: .binary)
        indexDescription1.isAscending = true
        let index1 = NSFetchIndexDescription(name: "com_mc_index_post_createdDate", elements: [indexDescription1])

        let indexDescription2 = NSFetchIndexElementDescription(property: attributeID, collationType: .binary)
        indexDescription2.isAscending = true
        let index2 = NSFetchIndexDescription(name: "com_mc_index_post_id", elements: [indexDescription2])

        let entity = NSEntityDescription()
        entity.name = PostEntity.entityName
        entity.managedObjectClassName = PostEntity.entityClassName
        entity.properties = [attributeCreatedDate, attributeID, attributeVideoURL, ...]
        entity.renamingIdentifier = "com.mc.entity-post"
        entity.indexes = [index1, index2]

        return entity
    }

}

Here is a debugger output:

po entity.indexes
▿ 2 elements
  - 0 : <NSFetchIndexDescription : (PostEntity:com.mc.index-post.createdDate, elements: (
    "<NSFetchIndexElementDescription : (createdDate (modeled property), 0, ascending)>"
), predicate: (null))>
  - 1 : <NSFetchIndexDescription : (PostEntity:com.mc.index-post.id, elements: (
    "<NSFetchIndexElementDescription : (id (modeled property), 0, ascending)>"
), predicate: (null))>

Upvotes: 3

Related Questions