NSFetchedResultsController with sections created by first letter of a string

后端 未结 7 1519
再見小時候
再見小時候 2020-11-28 01:09

Learning Core Data on the iPhone. There seem to be few examples on Core Data populating a table view with sections. The CoreDataBooks example uses sections, but they\'re ge

7条回答
  •  忘掉有多难
    2020-11-28 02:00

    I think I've got yet another option, this one uses a category on NSString...

    @implementation NSString (FetchedGroupByString)
    - (NSString *)stringGroupByFirstInitial {
        if (!self.length || self.length == 1)
            return self;
        return [self substringToIndex:1];
    }
    @end
    

    Now a little bit later on, while constructing your FRC:

    - (NSFetchedResultsController *)newFRC {
        NSFetchedResultsController *frc = [[NSFetchedResultsController alloc] initWithFetchRequest:awesomeRequest
                managedObjectContext:coolManagedObjectContext
                sectionNameKeyPath:@"lastName.stringGroupByFirstInitial"
                cacheName:@"CoolCat"];
        return frc;
    }
    

    This is now my favorite approach. Much cleaner/easier to implement. Moreover, you don't have to make any changes to your object model class to support it. This means that it'll work on any object model, provided the section name points to a property based on NSString

提交回复
热议问题