How to use the first character as a section name

后端 未结 6 1949
执念已碎
执念已碎 2020-11-27 09:54

I\'m using Core Data for a table view, and I\'d like to use the first letter of each of my results as the section header (so I can get the section index on the side). Is the

6条回答
  •  悲&欢浪女
    2020-11-27 10:27

    There may be a more elegant way to do this, but I recently had the same problem and came up with this solution.

    First, I defined a transient property on the objects I was indexing called firstLetterOfName, and wrote the getter into the .m file for the object. e.x.

    - (NSString *)uppercaseFirstLetterOfName {
        [self willAccessValueForKey:@"uppercaseFirstLetterOfName"];
        NSString *stringToReturn = [[self.name uppercaseString] substringToIndex:1];
        [self didAccessValueForKey:@"uppercaseFirstLetterOfName"];
        return stringToReturn;
    }
    

    Next, I set up my fetch request/entities to use this property.

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Object" inManagedObjectContext:dataContext];
    [request setEntity:entity];
    [NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)];
    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    [request setSortDescriptors:sortDescriptors];
    

    Side note, apropos of nothing: Be careful with NSFetchedResultsController — it's not exactly fully baked yet IMHO, and any situation beyond the simple cases listed in the documentation, you will probably be better off doing it the 'old fashioned' way.

提交回复
热议问题