Core data: any way to fetch multiple entities?

后端 未结 3 1368
情话喂你
情话喂你 2020-12-13 15:23

I\'m just getting started with Core Data, and as a learning exercise I\'m building an app where I need to display different types of objects in a single table view.

3条回答
  •  粉色の甜心
    2020-12-13 15:46

    I had to deal with this issue as well. Wanted to be able to search multiple entities but avoid inheritance that results in hierarchy of objects all stored in a single core data class and the performance issues that may result.

    I opted for creating a concrete Searchable object that stores searchable terms common among the objects I want to search against. This object was added to each of the classes I wanted to search for:

    Person.Searchable
    Employee.Searchable
    Department.Searchable
    

    Searchable has fields such at searchTerm and to many relationships with each of the objects I need to search for. And a displayName so that the information can be shown to the user without having to query/load any other table.

    Core Data queries are executed against Searchable so you only query a single entity.

    Example:

    Person { firstName = Joe, lastName = Jackson } -> searchable { term = joejackson, displayName = Joe Jackson, type = person }
    Employee { firstName = Joe, lastName = Smith } -> searchable { term = joesmith, displayName = Joe Smith, type = employee }
    Group { name = Joe’s Development Team } -> searchable { term = joesdevelopmentteam, displayName = Joe’s Development Team, type = group }
    

    Now you can list and search for Person, Employee, Department all separate tables using their Searchable member using a single Fetched Request Controller.

提交回复
热议问题