私のアプリケーションでは、コアデータに日付を文字列として挿入しています。これらの日付を昇順または降順で取得するにはどうすればよいですか。以下のコードを使用して、コアデータから日付文字列を取得し、結果をセクション テーブルに表示し、取得した日付をセクション タイトルとして表示しています。
- (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 @"";
}
しかし、日付文字列は昇順または降順のいずれかではありません。誰でも私の問題を解決できますか。事前に感謝します。