Write native SQL in Core Data

前端 未结 3 868
别那么骄傲
别那么骄傲 2021-01-22 19:15

I need to write a native SQL Query while I\'m using Core Data in my project. I really need to do that, since I\'m using NSPredicate right now and it\'s not efficien

相关标签:
3条回答
  • 2021-01-22 19:44

    If you want to use Core Data there is no supported way to do a SQL query. You can fetch specific values and use [NSExpression expressionForFunction:arguments:] with a sum: function.

    To see what SQL commands Core Data executes add -com.apple.CoreData.SQLDebug 1 to "Arguments Passed on Launch". Note that this should not tempt you to use the SQL commands youself, it's just for debugging purposes.

    0 讨论(0)
  • 2021-01-22 19:47

    Short answer: you can't do this.

    Long answer: Core Data is not a database per se - it's not guaranteed to have anything relational backing it, let alone a specific version of SQLite that you can query against. Furthermore, going mucking around in Core Data's persistent store files is a recipe for disaster, especially if Apple decides to change the format of that file in some way. You should instead try to find better ways to optimize your usage of NSPredicate or start caching the values you care about yourself.

    Have you considered using the KVC collection operators? For example, if you have an entity Foo each with a bunch of children Bar, and those Bars have a Baz integer value, I think you can get the sum of those for each Foo by doing something like:

    foo.bars.@sum.baz
    

    Not sure if these are applicable to predicates, but it's worth looking into.

    0 讨论(0)
  • 2021-01-22 19:50

    This is a bit of a hack, but... The SQLite library is capable of opening more than one database file at a given time. It would be quite feasible to open the Core Data DB file (read/only usage) directly with SQLite and open a second file in conjunction with this (reporting/temporary tables). One could then execute direct SQL queries on the data in the Core Data DB and persist them into a second file (if persistence is needed).

    I have done this sort of thing a few times. There are features available in the SQLite library (example: full-text search engine) that are not exposed through Core Data.

    0 讨论(0)
提交回复
热议问题