NSFetchedResultsController with sections created by first letter of a string

后端 未结 7 1521
再見小時候
再見小時候 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

    Here's how you might get it to work:

    • Add a new optional string attribute to the entity called "lastNameInitial" (or something to that effect).
    • Make this property transient. This means that Core Data won't bother saving it into your data file. This property will only exist in memory, when you need it.
    • Generate the class files for this entity.
    • Don't worry about a setter for this property. Create this getter (this is half the magic, IMHO)

      - (NSString *) lastNameInitial {
      [self willAccessValueForKey:@"lastNameInitial"];
      NSString * initial = [[self lastName] substringToIndex:1];
      [self didAccessValueForKey:@"lastNameInitial"];
      return initial;
      }
    • In your fetch request, request ONLY this PropertyDescription, like so (this is another quarter of the magic):

      NSDictionary * entityProperties = [myEntityDescription propertiesByName];
      NSPropertyDescription * lastNameInitialProperty = [entityProperties objectForKey:@"lastNameInitial"];
      [fetchRequest setPropertiesToFetch:[NSArray arrayWithObject:lastNameInitialProperty]];
    • Make sure your fetch request ONLY returns distinct results (this is the last quarter of the magic):

      [fetchRequest setReturnsDistinctResults:YES];
    • Order your results by this letter:

      NSSortDescriptor * lastNameInitialSortOrder = [[[NSSortDescriptor alloc] initWithKey:@"lastNameInitial" ascending:YES] autorelease];
      [fetchRequest setSortDescriptors:[NSArray arrayWithObject:lastNameInitialSortOrder]];
    • execute the request, and see what it gives you.

    If I understand how this works, then I'm guessing it will return an array of NSManagedObjects, each of which only has the lastNameInitial property loaded into memory, and who are a set of distinct last name initials.

    Good luck, and report back on how this works. I just made this up off the top of my head and want to know if this works. =)

提交回复
热议问题