I've been working on an iphone project and have run into an issue. Currently In the table view where it displays all the objects, I use headers based on the objects datePerformed field. The only problem is that my code apparently creates a header that contains both the date and time resulting in objects not being grouped solely by their date as I intended, but rather based on their date and time. I'm not sure if it matters, but when an object is created I use a date picker to pick the date, but not the time. I was wondering if anyone could give me any suggestions or advice.
Here is the code where i set up the fetchedResultsController
- (NSFetchedResultsController *)fetchedResultsController {
if (fetchedResultsController != nil) {
return fetchedResultsController;
}
// Create and configure a fetch request with the Exercise entity.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Exercise" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
// Create the sort descriptors array using date and name
NSSortDescriptor *dateDescriptor = [[NSSortDescriptor alloc] initWithKey:@"datePerformed" ascending:NO];
NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" asc开发者_如何转开发ending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:dateDescriptor, nameDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
// Create and initialize the fetch results controller
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:@"datePerformed" cacheName:@"Root"];
self.fetchedResultsController = aFetchedResultsController;
fetchedResultsController.delegate = self;
// Memory management calls
[aFetchedResultsController release];
[fetchRequest release];
[dateDescriptor release];
[nameDescriptor release];
[sortDescriptors release];
return fetchedResultsController;
}
Here's where I set up the table header properties:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
// Display the exercise' date as section headings.
return [[[fetchedResultsController sections] objectAtIndex:section] name];
}
Any suggestions welcome.
When you convert the NSDate to a string for the table, just convert the date and not the time. One of my apps does this exact thing for the table headers, I configure the date formatter this way (no time style):
self.dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString* str = [dateFormatter stringFromDate:[NSDate date]];
You might need to add this line if you are using a formatter that already has a time style set:
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
精彩评论