如果你使用 coreData,你可以扩展你UITableView
的NSFetchedResultsController
首先在持有的类中添加委托UITableView
// MyClass.h
MyClass : UITableViewController<NSFetchedResultsControllerDelegate>
{
NSFetchedResultsController *fetchedResultsController;
// ...
}
// MyClass.m
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSError *error = nil;
fetchedResultsController = nil;
if( ![[self fetchedResultsController] performFetch:&error] )
{
// Log the error and/or do something with it
abort();
}
[self.tableView reloadData];
}
- (NSFetchedResultsController *)fetchedResultsController
{
if( !fetchedResultsController )
{
// Create the fetch request for the entity.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:@"RecordList"
inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc] initWithKey:@"toDoPriority" ascending:YES];
NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc] initWithKey:@"toDoItem" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor1, sortDescriptor2, nil];
[sortDescriptor1 release];
[sortDescriptor2 release];
[fetchRequest setSortDescriptors:sortDescriptors];
// add predicate if you need
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"do I need a predicate?", things];
[fetchRequest setPredicate:predicate];
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:managedObjectContext
sectionNameKeyPath:nil
cacheName:@"MyRecordsCache"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
[aFetchedResultsController release];
[fetchRequest release];
[sortDescriptors release];
}
return fetchedResultsController;
}
--
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
static NSString CellIdentifier = @"Cell";
RecordList *records = [fetchedResultsController objectAtIndexPath:indexPath];
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
NSArray *xibPath = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
cell = (CustomCell *)[xibPath objectAtIndex:0];
}
cell.itemName.text =records.toDoItem;
cell.itemPriority.text = records.toDoPriority;
return cell;
}