在我的应用程序中,我将 coredata 中的日期作为字符串插入。如何按升序或降序获取这些日期。我使用下面的代码从 coredata 获取日期字符串并在节表中显示结果,并将获取的日期作为节标题。
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
-(IBAction)insert:(id)sender
{
NSManagedObjectContext *moc=[[self appDelegate] managedObjectContext];
StringDates *entity=[NSEntityDescription insertNewObjectForEntityForName:@"StringDates" inManagedObjectContext:moc];
entity.unused=insertTextField.text;
entity.message=@"123456789";
NSError *error;
[moc save:&error];
[insertTextField resignFirstResponder];
}
-(NSFetchedResultsController *)fetchedResultsController
{
NSManagedObjectContext *moc = [[self appDelegate] managedObjectContext];
if (moc == nil) return nil;
NSEntityDescription *entity = [NSEntityDescription entityForName:@"StringDates" inManagedObjectContext:moc];
NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:@"unused" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sd1,nil];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:entity];
[fetchRequest setSortDescriptors:sortDescriptors];
fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:moc sectionNameKeyPath:@"unused" cacheName:nil];
[fetchedResultsController setDelegate:self];
NSError *error = nil;
if (![fetchedResultsController performFetch:&error])
{
NSLog(@"Error performing fetch: %@", error);
}
return fetchedResultsController;
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
[stringDatesTableView reloadData];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [[[self fetchedResultsController] sections] count];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSArray *sections = [[self fetchedResultsController] sections];
if (section < [sections count])
{
id <NSFetchedResultsSectionInfo> sectionInfo = [sections objectAtIndex:section];
return sectionInfo.numberOfObjects;
}
return 0;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//static NSString *cellidenitifier=@"cell";
StringDates *userRecentChat=[[self fetchedResultsController] objectAtIndexPath:indexPath];
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:nil];
if(cell==nil)
{
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:nil];
}
cell.detailTextLabel.text=userRecentChat.message;
return cell;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSArray *sections = [[self fetchedResultsController] sections];
if (section < [sections count])
{
id <NSFetchedResultsSectionInfo> sectionInfo = [sections objectAtIndex:section];
return sectionInfo.name;
}
return @"";
}
但是日期字符串既没有按顺序排列,也没有按顺序排列。谁能解决我的问题。谢谢。