Ios 如何使用核心数据实现表节
我正在iOS应用程序中使用核心数据。我有一个tableview来显示来自一个名为persons的实体的数据。实体人员有几个属性,其中一个属性是“日期”。我想在表视图中创建5个永久部分(0.今天,1.明天,2.本周,3.本月,4.即将到来),然后我想根据日期在每个部分上显示数据。 我一直在搜索这个问题,但没有找到可以应用于我的应用程序的问题。 我恳请你告诉我正确的处理方法 这是我目前的代码:Ios 如何使用核心数据实现表节,ios,core-data,uitableview,Ios,Core Data,Uitableview,我正在iOS应用程序中使用核心数据。我有一个tableview来显示来自一个名为persons的实体的数据。实体人员有几个属性,其中一个属性是“日期”。我想在表视图中创建5个永久部分(0.今天,1.明天,2.本周,3.本月,4.即将到来),然后我想根据日期在每个部分上显示数据。 我一直在搜索这个问题,但没有找到可以应用于我的应用程序的问题。 我恳请你告诉我正确的处理方法 这是我目前的代码: #import "PersonsTVC.h" #import "Person.h" @implement
#import "PersonsTVC.h"
#import "Person.h"
@implementation PersonsTVC
@synthesize fetchedResultsController = __fetchedResultsController;
@synthesize managedObjectContext = __managedObjectContext;
@synthesize selectedPerson;
@synthesize searchResults,titulosseccion;
- (void)setupFetchedResultsController
{
// 1 - Decide what Entity you want
NSString *entityName = @"Person"; // Put your entity name here
NSLog(@"Setting up a Fetched Results Controller for the Entity named %@", entityName);
// 2 - Request that Entity
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:entityName];
// 3 - Filter it if you want
//request.predicate = [NSPredicate predicateWithFormat:@"Person.name = Blah"];
// 4 - Sort it if you want
request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"firstname"
ascending:YES
selector:@selector(localizedCaseInsensitiveCompare:)]];
// 5 - Fetch it
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
[self performFetch];
}
- (void) viewDidLoad
{
self.searchResults = [NSMutableArray arrayWithCapacity:[[self.fetchedResultsController fetchedObjects] count]];
[self.tableView reloadData];
}
-(void) viewDidUnload{
self.searchResults = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self setupFetchedResultsController];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [[self.fetchedResultsController sections] count];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Perform segue to detail when a SEARCH table cell is touched
if(tableView == self.searchDisplayController.searchResultsTableView)
{
[self performSegueWithIdentifier:@"Person Detail Segue" sender:tableView];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Persons Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
// Configure the cell...
Person *person = nil;
if (tableView == self.searchDisplayController.searchResultsTableView)
{
NSLog(@"Configuring cell to show search results");
person = [self.searchResults objectAtIndex:indexPath.row];
}
else
{
NSLog(@"Configuring cell to show normal data");
person = [self.fetchedResultsController objectAtIndexPath:indexPath];
}
NSString *fullname = [NSString stringWithFormat:@"%@ %@", person.firstname, person.surname];
cell.textLabel.text = person.firstname;
if ([person.inRole.color isEqual :@"Yellow"])
{
cell.imageView.image = [UIImage imageNamed:@"Yellow"];
}
if ([person.inRole.color isEqual :@"Black"])
{
cell.imageView.image = [UIImage imageNamed:@"Black"];
}
if ([person.inRole.color isEqual :@"Grey"])
{
cell.imageView.image = [UIImage imageNamed:@"Grey"];
}
if ([person.inRole.color isEqual :@"Red"])
{
cell.imageView.image = [UIImage imageNamed:@"Red"];
}
if ([person.inRole.color isEqual :@"Blue"])
{
cell.imageView.image = [UIImage imageNamed:@"Blue"];
}
if ([person.inRole.color isEqual :@"Dark Green"])
{
cell.imageView.image = [UIImage imageNamed:@"DarkGreen"];
}
if ([person.inRole.color isEqual :@"Light Green"])
{
cell.imageView.image = [UIImage imageNamed:@"LightGreen"];
}
if ([person.inRole.color isEqual :@"Light Blue"])
{
cell.imageView.image = [UIImage imageNamed:@"LightBlue"];
}
if ([person.inRole.color isEqual :@"Brown"])
{
cell.imageView.image = [UIImage imageNamed:@"Brown"];
}
if ([person.inRole.color isEqual :@"Dark Orange"])
{
cell.imageView.image = [UIImage imageNamed:@"DarkOrange"];
}
NSDate *fechasinformat = person.date;
NSString *fecha0 = [NSString stringWithFormat:@"%@", fechasinformat];
cell.detailTextLabel.text = fecha0;
return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.searchDisplayController.searchResultsTableView)
{
return [self.searchResults count];
}
else
{
return [[[self.fetchedResultsController sections] objectAtIndex:section] numberOfObjects];
}
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
[self.tableView beginUpdates]; // Avoid NSInternalInconsistencyException
// Delete the person object that was swiped
Person *personToDelete = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSLog(@"Deleting (%@)", personToDelete.firstname);
[self.managedObjectContext deleteObject:personToDelete];
[self.managedObjectContext save:nil];
// Delete the (now empty) row on the table
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[self performFetch];
[self.tableView endUpdates];
}
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"Add Person Segue"])
{
NSLog(@"Setting PersonsTVC as a delegate of PersonDetailTVC");
PersonDetailTVC *personDetailTVC = segue.destinationViewController;
personDetailTVC.delegate = self;
NSLog(@"Creating a new person and passing it to PersonDetailTVC");
Person *newPerson = [NSEntityDescription insertNewObjectForEntityForName:@"Person"
inManagedObjectContext:self.managedObjectContext];
personDetailTVC.person = newPerson;
}
else if ([segue.identifier isEqualToString:@"Person Detail Segue"])
{
NSLog(@"Setting PersonsTVC as a delegate of PersonDetailTVC");
PersonDetailTVC *personDetailTVC = segue.destinationViewController;
personDetailTVC.delegate = self;
// Store selected Person in selectedPerson property
if(sender == self.searchDisplayController.searchResultsTableView)
{
NSIndexPath *indexPath = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow];
self.selectedPerson = [self.searchResults objectAtIndex:[indexPath row]];
}
else
{
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
self.selectedPerson = [self.fetchedResultsController objectAtIndexPath:indexPath];
}
NSLog(@"Passing selected person (%@) to PersonDetailTVC", self.selectedPerson.firstname);
personDetailTVC.person = self.selectedPerson;
}
else
{
NSLog(@"Unidentified Segue Attempted!");
}
}
- (void)theSaveButtonOnThePersonDetailTVCWasTapped:(PersonDetailTVC *)controller
{
// do something here like refreshing the table or whatever
// close the delegated view
[controller.navigationController popViewControllerAnimated:YES];
}
#pragma mark -
#pragma mark Content Filtering
-(void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope {
self.searchResults = [[self.fetchedResultsController fetchedObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
Person* person = evaluatedObject;
NSString* firstName = person.firstname;
//searchText having length < 3 should not be considered
if (!!searchText && [searchText length] < 3) {
return YES;
}
if ([scope isEqualToString:@"All"] || [firstName isEqualToString:scope]) {
return ([firstName rangeOfString:searchText].location != NSNotFound);
}
return NO; //if nothing matches
}]];
}
#pragma mark -
#pragma mark UISearchDisplayController Delegate Methods
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString scope:@"All"];
return YES;
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption
{
[self filterContentForSearchText:[self.searchDisplayController.searchBar text] scope:@"All"];
return YES;
}
@end
#导入“PersonsTVC.h”
#输入“Person.h”
@执行人员
@综合fetchedResultsController=\uu fetchedResultsController;
@综合managedObjectContext=u managedObjectContext;
@综合选人;
@综合搜索结果,Tituloseccion;
-(无效)setupFetchedResultsController
{
//1-决定您想要的实体
NSString*entityName=@“Person”//请在此处输入您的实体名称
NSLog(@“为名为%@的实体设置获取结果控制器”,entityName);
//2-请求该实体
NSFetchRequest*request=[NSFetchRequest fetchRequestWithEntityName:entityName];
//3-如果需要,可以对其进行过滤
//request.predicate=[NSPredicate predicateWithFormat:@“Person.name=Blah”];
//4-如果需要,请进行排序
request.sortDescriptors=[NSArray arrayWithObject:[NSSortDescriptor SortDescriptor WithKey:@“firstname”
上升:是的
选择器:@selector(localizedCaseInsensitiveCompare:)];
//5-拿过来
self.fetchedResultsController=[[NSFetchedResultsController alloc]initWithFetchRequest:request
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:无
cacheName:nil];
[自执行蚀刻];
}
-(无效)viewDidLoad
{
self.searchResults=[NSMutableArray阵列容量:[[self.fetchedResultsController fetchedObjects]计数]];
[self.tableView重载数据];
}
-(无效)视图卸载{
self.searchResults=nil;
}
-(无效)视图将显示:(BOOL)动画
{
[超级视图将显示:动画];
[自设置FetchedResultsController];
}
-(NSInteger)表格视图中的节数:(UITableView*)表格视图{
返回[[self.fetchedResultsController节]计数];
}
-(void)tableView:(UITableView*)tableView未选择RowatineXpath:(NSIndexPath*)indexPath
{
//触摸搜索表单元格时,执行segue to detail
if(tableView==self.searchDisplayController.searchResultsTableView)
{
[self-PerformsgueWithIdentifier:@“个人详细信息序列”发件人:tableView];
}
}
-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
静态NSString*CellIdentifier=@“个人单元格”;
UITableViewCell*单元格=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
如果(单元格==nil){
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault重用标识符:CellIdentifier];
}
//配置单元格。。。
//配置单元格。。。
人*人=零;
if(tableView==self.searchDisplayController.searchResultsTableView)
{
NSLog(@“配置单元格以显示搜索结果”);
person=[self.searchResults objectAtIndex:indexPath.row];
}
其他的
{
NSLog(@“配置单元格以显示正常数据”);
person=[self.fetchedResultsController对象索引路径:indexPath];
}
NSString*fullname=[NSString stringWithFormat:@“%@%@”,person.firstname,person.姓氏];
cell.textlab.text=person.firstname;
如果([person.inRole.color isEqual:@“Yellow”])
{
cell.imageView.image=[UIImage ImageName:@“黄色”];
}
如果([person.inRole.color isEqual:@“Black”])
{
cell.imageView.image=[UIImage ImageName:@“黑色”];
}
如果([person.inRole.color isEqual:@“Grey”])
{
cell.imageView.image=[UIImage ImageName:@“灰色”];
}
如果([person.inRole.color isEqual:@“Red”])
{
cell.imageView.image=[UIImage ImageName:@“红色”];
}
如果([person.inRole.color isEqual:@“Blue”])
{
cell.imageView.image=[UIImage ImageName:@“蓝色”];
}
如果([person.inRole.color isEqual:@“深绿色”])
{
cell.imageView.image=[UIImage ImageName:@“暗绿色”];
}
如果([person.inRole.color isEqual:@“浅绿色”])
{
cell.imageView.image=[UIImage ImageName:@“浅绿色”];
}
如果([person.inRole.color isEqual:@“浅蓝色”])
{
cell.imageView.image=[UIImage ImageName:@“LightBlue”];
}
如果([person.inRole.color isEqual:@“Brown”])
{
cell.imageView.image=[UIImage ImageName:@“Brown”];
}
如果([person.inRole.color isEqual:@“深橙色”])
{
cell.imageView.image=[UIImage ImageName:@“DarkOrange”];
}
NSDate*fechasformat=person.date;
NSString*fecha0=[NSString stringWithFormat:@“%@”,fechasinformat];
cell.detailTextLabel.text=fecha0;
返回单元;
}
-(NSInteger)表视图:(UITableView*)表视图行数节:(NSInteger)节
{
if(tableView==self.searchDisplayController.searchResultsTableView)
{
返回[self.searchResults计数];
}
其他的
{
返回[[[self.fetchedResultsController节]对象索引:节]numberOfObjects];
}
}
-(void)tableView:(UITableView*)tableView提交的编辑样式:(UITableViewCellEditingStyle)行的编辑样式索引路径:(NSIndexPath*)索引路径{
如果(editingStyle==UITableViewCellEditingStyleDelete){
[self.tableView-be
// First sort descriptor (required for grouping into sections):
NSSortDescriptor *sortByDate = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES];
// Second sort descriptor (for the items within each section):
NSSortDescriptor *sortByName = [[NSSortDescriptor alloc] initWithKey:@"firstname" ascending:YES];
[request setSortDescriptors:@[sortByDate, sortByName]];
- (NSString *)sectionIdentifier
{
[self willAccessValueForKey:@"sectionIdentifier"];
NSString *tmp = [self primitiveValueForKey:@"sectionIdentifier"];
[self didAccessValueForKey:@"sectionIdentifier"];
if (!tmp)
{
NSDate *date = self.date;
// Using pseudo-code here:
if ("date is from today") {
tmp = @"0";
} else if ("date is from tomorrow") {
tmp = @"1";
} else ... // and so on ...
[self setPrimitiveValue:tmp forKey:@"sectionIdentifier"];
}
return tmp;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
id <NSFetchedResultsSectionInfo> theSection = [[self.fetchedResultsController sections] objectAtIndex:section];
NSString *sectionName = [theSection name];
if ([sectionName isEqualToString:@"0"]) {
return @"Today";
} else if ([sectionName isEqualToString:@"1"]) {
return @"Tomorrow";
} ... // and so on ...
} else {
return @"Other";
}
}