How to sort Core Data fetched properties

前端 未结 8 2051
太阳男子
太阳男子 2020-12-12 15:30

The Core Data Documentation states that:

The fetch request associated with the [fetched] property can have a sort ordering, and thus the fetched prope

8条回答
  •  既然无缘
    2020-12-12 15:57

    You can actually grab the model fetched property and add the sort descriptors to it (again, in code). I did this in the standard method that XCode generates in your AppDelegate if you choose one of the templates with Core Data:

    By the way. This sorts ALL fetched properties on ALL models in your data model. You could get fancy and adaptive with it, but it was the most succinct way to handle sorting the 7 separate models that each had fetched properties that needed to be sorted by name. Works well.

    /**
     Returns the managed object model for the application.
     If the model doesn't already exist, it is created by merging all of the models found in the application bundle.
     */
    - (NSManagedObjectModel *)managedObjectModel {
    
        if (managedObjectModel != nil) {
            return managedObjectModel;
        }
        managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];    
    
        // Find the fetched properties, and make them sorted...
        for (NSEntityDescription *entity in [managedObjectModel entities]) {
            for (NSPropertyDescription *property in [entity properties]) {
                if ([property isKindOfClass:[NSFetchedPropertyDescription class]]) {
                    NSFetchedPropertyDescription *fetchedProperty = (NSFetchedPropertyDescription *)property;
                    NSFetchRequest *fetchRequest = [fetchedProperty fetchRequest];
    
                    // Only sort by name if the destination entity actually has a "name" field
                    if ([[[[fetchRequest entity] propertiesByName] allKeys] containsObject:@"name"]) {
                        NSSortDescriptor *sortByName = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
                        [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortByName]];
                        [sortByName release];
                    }
                }
            }
        }
    
        return managedObjectModel;
    }
    

提交回复
热议问题