我找到了实现section collapsable / expandible tableView所需的方法,但是它从代码本身填充了行对象。我刚刚创建了一个核心数据实体,并希望知道用它填充行对象。我需要帮助转换这个特定的代码,让我添加核心数据对象。 这是我目前的代码:
//
#import "CollapsableTableViewViewController.h"
#import "CollapsableTableView.h"
#import "CollapsableTableViewAppDelegate.h"
@interface CollapsableTableViewViewController()
@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;
@end
@implementation CollapsableTableViewViewController
@synthesize fetchedResultsController = _fetchedResultsController;
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
*/
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
//1
CollapsableTableViewAppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
//2
self.managedObjectContext = appDelegate.managedObjectContext;
self.fetchedResultsController = nil;
NSError *error;
if (![[self fetchedResultsController] performFetch:&error]) {
// Update to handle the error appropriately.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
exit(-1); // Fail
}
CollapsableTableView* tableView = (CollapsableTableView*) myTableView;
tableView.collapsableTableViewDelegate = self;
// [tableView setIsCollapsed:YES forHeaderWithTitle:@"First Section"];
// [tableView setIsCollapsed:YES forHeaderWithTitle:@"Second Section"];
// [tableView setIsCollapsed:YES forHeaderWithTitle:@"Third Section"];
// [tableView setIsCollapsed:YES forHeaderWithTitle:@"Fourth Section"];
// [tableView setIsCollapsed:YES forHeaderWithTitle:@"Fifth Section"];
}
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return YES;
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
[spinner release];
spinner = nil;
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[spinner release];
[super dealloc];
}
#pragma mark -
#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 10;
}
+ (NSString*) titleForHeaderForSection:(int) section
{
switch (section)
{
case 0 : return @"First Section";
case 1 : return @"Second Section";
case 2 : return @"Third Section";
case 3 : return @"Fourth Section";
case 4 : return @"Fifth Section";
default : return [NSString stringWithFormat:@"Section no. %i",section + 1];
}
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [CollapsableTableViewViewController titleForHeaderForSection:section];
}
// Uncomment the following two methods to use custom header views.
//- (UILabel *) createHeaderLabel: (UITableView *) tableView :(NSString *)headerTitle {
// UILabel *titleLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
// titleLabel.frame =CGRectMake(0, 0, tableView.frame.size.width - 20, 60);
// titleLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
// titleLabel.backgroundColor = [UIColor clearColor];
// titleLabel.textColor = [UIColor whiteColor];
// titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:20];
// titleLabel.text = headerTitle;
// titleLabel.textAlignment = UITextAlignmentRight;
// return titleLabel;
//}
//
//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
// // create the parent view that will hold header Label
// UIView * customView = [[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, tableView.frame.size.width , 60)]autorelease];
// UILabel *titleLabel;
// titleLabel = [self createHeaderLabel: tableView :[CollapsableTableViewViewController titleForHeaderForSection:section]];
//
// [customView addSubview:titleLabel];
//
// UILabel* collapsedLabel = [[[UILabel alloc] initWithFrame:CGRectMake(10,0,50,60)] autorelease];
// collapsedLabel.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
// collapsedLabel.backgroundColor = [UIColor clearColor];
// collapsedLabel.textColor = [UIColor whiteColor];
// collapsedLabel.text = @"-";
// collapsedLabel.tag = COLLAPSED_INDICATOR_LABEL_TAG;
// [customView addSubview:collapsedLabel];
//
// customView.tag = section;
// customView.backgroundColor = [UIColor blackColor];
// return customView;
//}
//- (NSString*) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
//{
// return [NSString stringWithFormat:@"Footer %i",section + 1];
//}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
switch (section)
{
case 2 : return 0;
case 3 : return 30;
default : return 8;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
switch (indexPath.row)
{
case 0 : cell.textLabel.text = @"First Cell"; break;
case 1 : cell.textLabel.text = @"Second Cell"; break;
case 2 : cell.textLabel.text = @"Third Cell"; break;
case 3 : cell.textLabel.text = @"Fourth Cell"; break;
case 4 : cell.textLabel.text = @"Fifth Cell"; break;
case 5 : cell.textLabel.text = @"Sixth Cell"; break;
case 6 : cell.textLabel.text = @"Seventh Cell"; break;
case 7 : cell.textLabel.text = @"Eighth Cell"; break;
default : cell.textLabel.text = [NSString stringWithFormat:@"Cell %i",indexPath.row + 1];
}
//cell.detailTextLabel.text = ...;
return cell;
}
#pragma mark -
#pragma mark CollapsableTableViewDelegate
- (void) collapsableTableView:(CollapsableTableView*) tableView willCollapseSection:(NSInteger) section title:(NSString*) sectionTitle headerView:(UIView*) headerView
{
[spinner startAnimating];
}
- (void) collapsableTableView:(CollapsableTableView*) tableView didCollapseSection:(NSInteger) section title:(NSString*) sectionTitle headerView:(UIView*) headerView
{
[spinner stopAnimating];
}
- (void) collapsableTableView:(CollapsableTableView*) tableView willExpandSection:(NSInteger) section title:(NSString*) sectionTitle headerView:(UIView*) headerView
{
[spinner startAnimating];
}
- (void) collapsableTableView:(CollapsableTableView*) tableView didExpandSection:(NSInteger) section title:(NSString*) sectionTitle headerView:(UIView*) headerView
{
[spinner stopAnimating];
}
#pragma mark -
#pragma mark IBAction methods
- (IBAction) toggleSection2
{
NSString* sectionTitle = //[NSString stringWithFormat:@"Tag %i",1]; // Use this expression when using custom header views.
[CollapsableTableViewViewController titleForHeaderForSection:1]; // Use this expression when specifying text for headers.
CollapsableTableView* collapsableTableView = (CollapsableTableView*) myTableView;
BOOL isCollapsed = [[collapsableTableView.headerTitleToIsCollapsedMap objectForKey:sectionTitle] boolValue];
[collapsableTableView setIsCollapsed:! isCollapsed forHeaderWithTitle:sectionTitle];
}
- (NSFetchedResultsController *)fetchedResultsController {
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"ToDoItems" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSSortDescriptor *sort = [[NSSortDescriptor alloc]
initWithKey:@"tdText" ascending:NO];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
[fetchRequest setFetchBatchSize:20];
NSFetchedResultsController *theFetchedResultsController =
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil
cacheName:@"Root"];
self.fetchedResultsController = theFetchedResultsController;
_fetchedResultsController.delegate = self;
return _fetchedResultsController;
}
@end
要向我的应用添加核心数据,我已完成以下操作:
1. Added CoreDataFramework to the project.
2. Added #import <CoreData/CoreData.h> to the prefix.pch file
3. Added
@property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
@property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
@property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator ;
to my AppDelegate.h file
4. Added
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
到我的AppDelegate.m文件。
5. Added
//core data
// 1
- (NSManagedObjectContext *) managedObjectContext {
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator: coordinator];
}
return _managedObjectContext;
}
//2
- (NSManagedObjectModel *)managedObjectModel {
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
_managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
return _managedObjectModel;
}
//3
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory]
stringByAppendingPathComponent: @"Model.sqlite"]];
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]
initWithManagedObjectModel:[self managedObjectModel]];
if(![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil URL:storeUrl options:nil error:&error]) {
/*Error for store creation should be handled in here*/
}
return _persistentStoreCoordinator;
}
- (NSString *)applicationDocumentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
到我的AppDelegate.m文件
6. Updated VC as new edited above in the question.
答案 0 :(得分:0)
我发现使用UITableView的CoreData的最佳开端实际上是基于Xcode模板“启用了核心数据的主要详细信息应用程序”的新“从头开始”项目。在此模板中,您将看到所有必须使用CoreData实体填充UITableView的样板代码。
相信我:有太多的基础设施要做 - 你无法“猜测”这段代码或者从API描述中获取,或者从其他地方读取。但是,如果您打开现有项目和这个新模板项目。然后慢慢滚动MasterViewController的代码并复制&amp;粘贴所有你需要的。这将为您提供一个非常快速的开始。
至少它在同样的情况下对我有用。