开发者

First Letter Section Headers with Core Data

I'm trying to create a list of people sorted in a tableView of sections with the first letter as the title for each section - a la Address Book. I've got it all working, though there is a bit of an issue with the sort order. Here is the way I'm doing it now:

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Contact" inManagedObjectContext:context]];

NSSortD开发者_JS百科escriptor *fullName = [[NSSortDescriptor alloc] initWithKey:@"fullName" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:fullName, nil];
[request setSortDescriptors:sortDescriptors];
[fullName release];
[sortDescriptors release];

NSError *error = nil;
[resultController release];
resultController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:context sectionNameKeyPath:@"firstLetter" cacheName:nil];
[resultController performFetch:&error];
[request release];

fullName is a standard property, and firstLetter is a transient property which returns - as you'd expect - the first letter of the fullName. 95% of the time, this works perfectly.

The problem is the result controller expects these two "lists" (the sorted fullName list and the sorted firstLetter list) to match exactly. If I have 2 contacts like John and Jack, my fullName list would sort these as Jack, John every time but my firstLetter list might sort them as John, Jack sometimes as it's only sorting by the first letter and leaving the rest to chance. When these lists don't match up, I get a blank tableView with 0 items in it.

I'm not really sure how I should go about fixing this issue, but it's very frustrating. Has anyone else run into this? What did you guys find out?


I am confused by what you mean by "first letter list".

You should not be creating such a list. You only implement the getter for the transient "firstLetter" property and use the fetched results controller's boiler-plate methods to implement the table view methods.

See this answer to How to use the first character as a section name for details.


I have not played with the section index too much but one thought would be to add the firstLetter sort as the first sort on your NSFetchRequest and add the fullName sort as a second sort.

If that doesn't work it would be great if you could post a sample project with the error so that we can play with it. If it turns out to be an Apple bug that same sample project can be used to submit the radar. If its not you are more likely to get someone to help solve it when they don't have to create the same project and try to rediscover the bug.

Plus there is always the off chance in the sample project that you stumble upon the answer. Happens to me all the time :)

UPDATE

I prefer Gerry3's answer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜