为了规避 NSFetchedResultsController 固有的一些问题,我决定将我的 UITableViewController 更改为 UIViewController 并添加一个 tableView 属性。我没有使用故事板,而是以编程方式制作所有内容。这样做的目的是在 y 轴上从顶部开始留下大约 44 px 的空白空间(这样我可以在那里放置一个通用标题)的表格视图。基本上,我试图将 tableview 向下移动 44 px。
问题是,我在 fetchedResultsController 处遇到断点错误。这是我的代码:
视图控制器.h
@interface ToDoViewController : UIViewController <UITableViewDelegate, SettingsViewControllerDelegate, NSFetchedResultsControllerDelegate, UITableViewDataSource>
@property (nonatomic) NSManagedObjectContext *managedObjectContext;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic) NSFetchedResultsController *fetchedResultsController;
@end
视图控制器.m
@implementation ToDoViewController
@synthesize managedObjectContext;
@synthesize fetchedResultsController = _fetchedResultsController;
@synthesize tableView = _tableView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
UINavigationItem *i = [self navigationItem];
[i setTitle:@"Task List"];
_tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 44, 320, 548) style:UITableViewStyleGrouped];
[self.view addSubview:self.tableView];
self.tableView = self.fetchedResultsController.delegate;
}
return self;
-(void) viewDidLoad{
[super viewDidLoad];
NSError *error;
if (![[self fetchedResultsController] performFetch:&error]){
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
exit(-1);
}
[self.tableView setDelegate:self];
[self.tableView setDataSource:self];
[self.tableView setBackgroundView:nil];
[self.tableView setBackgroundColor:baseColor];
[self.view setBackgroundColor:baseColor];
- (NSFetchedResultsController *)fetchedResultsController {
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"Tasks" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSSortDescriptor *isCompleted = [[NSSortDescriptor alloc]initWithKey:@"sectionString" ascending:NO];
NSSortDescriptor *sort = [[NSSortDescriptor alloc]
initWithKey:@"dateCreated" ascending:YES];
[fetchRequest setSortDescriptors:@[isCompleted, sort]];
[fetchRequest setFetchBatchSize:20];
NSFetchedResultsController *theFetchedResultsController =
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"sectionString"
cacheName:nil];
self.fetchedResultsController = theFetchedResultsController;
_fetchedResultsController.delegate = self;
return _fetchedResultsController;
}
问题是表格视图没有填充应该由 nsfetchedresultscontroller 获取的项目。我不知道为什么会这样……也许是因为 tableview 不是委托或其他什么?