How to sort Core Data fetched properties

前端 未结 8 2029
太阳男子
太阳男子 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 16:01

    Jeff, if the strings are right-aligned, you could just sort on the strings; " 123" > " 23" and so on. But iirc ascii space is after the numbers, and if so, then what you would do is create a dynamic property that is an NSNumber (which supports the compare: method), and use the numberFromString: method to make a number from the string. Then you can specify the number field in the sort. In the interface:

    @property NSString *stringIsaNumber; // in the data model
    @property NSNumber *number;
    

    in the implementation:

    @dynamic stringIsaNumber; 
    - (NSNumber *) number ;
    { return [self.stringIsaNumber numberFromString]; }
    - (void) setNumber:(NSNumber *)value;
    { self.stringIsaNumber = [NSString stringWithFormat:@"%5i",value) }
    

    ps plz forgive coding errors, this is off the top of my head.

    0 讨论(0)
  • 2020-12-12 16:04

    Using Tim Shadel's great answer I added per-NSManagedObject subclass sorting...

    ...in Tier.m (which is a NSManagedObject subclass)...

    + (void)initialize
    {
        if(self == [Tier class])
        {
            NSFetchedPropertyDescription *displayLessonPropertyDescription = [[[Tier entityDescription] propertiesByName] objectForKey:@"displayLesson"];
            NSFetchRequest *fetchRequest = [displayLessonPropertyDescription fetchRequest];
    
            NSSortDescriptor *sortByName = [[NSSortDescriptor alloc] initWithKey:@"displayOrder" ascending:YES];
           [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortByName]];
            [sortByName release];
        }
    }
    
    0 讨论(0)
提交回复
热议问题