Search code examples
core-datansfetchrequestnssortdescriptor

Add NSSortDescriptor to Fetch Request in Managed Object Context?


I created a Fetch Request "MyRequest" in the visual editor for my Core Data Model (where you also can visually add Entities as well). Now that the fetch request is created, how can I add a sort descriptor to it? If I retrieve it from the managed object model programmatically, it does not allow me to add a sort descriptor to it, as it says I am not allowed to make changes to an immutable object in the model. ..


Solution

  • fetchRequestTemplateForName: returns an immutable fetch request as it is stored in the model, but fetchRequestFromTemplateWithName:substitutionVariables: creates a new fetch request that can be modified.

    If you don't have any substitution variables, you can use an empty dictionary for that parameter:

    NSFetchRequest *request = [managedObjectModel fetchRequestFromTemplateWithName:@"name" substitutionVariables:@{}];
    NSSortDescriptor *desc = ...;
    [request setSortDescriptors:@[desc]];