Cocoa touch 核心数据NSFetchedResultsController代码缩短
所以,我对核心数据非常陌生,决定使用神奇记录来减少LOC 在我的第一个视图中,我有一个公司列表,每个公司有N个用户 目前,我设法让一切正常工作,但我的代码太长了 我想做的是缩短代码,因为我知道我可以,我只是不知道怎么做 如果查看下面的代码,您将看到在调用NSFetchedResultsController时使用的公用行Cocoa touch 核心数据NSFetchedResultsController代码缩短,cocoa-touch,core-data,magicalrecord,nsfetchedresultscontroller,Cocoa Touch,Core Data,Magicalrecord,Nsfetchedresultscontroller,所以,我对核心数据非常陌生,决定使用神奇记录来减少LOC 在我的第一个视图中,我有一个公司列表,每个公司有N个用户 目前,我设法让一切正常工作,但我的代码太长了 我想做的是缩短代码,因为我知道我可以,我只是不知道怎么做 如果查看下面的代码,您将看到在调用NSFetchedResultsController时使用的公用行 [self.fetchedResultsController.sections[0]objects] 有没有办法减少这种情况,这样我就不必访问NSFRC的索引0? 我能做点像这
[self.fetchedResultsController.sections[0]objects]
有没有办法减少这种情况,这样我就不必访问NSFRC的索引0?
我能做点像这样的事吗
self.fetchedResultsController = [self.fetchedResultsController.sections[0]objects]
谢谢你的时间
更新:
我想我可以从fetchedresults控制器获取一个数组并使用它
NSArray *companies = [NSArray arrayWithArray:[self.fetchedResultsController.sections[0]objects]];
我的对象还会保持相同的内存地址吗
#pragma mark Fetched results controller
- (NSFetchedResultsController *)fetchedResultsController {
// Set up the fetched results controller if needed.
if (_fetchedResultsController == nil) {
self.fetchedResultsController = [Company MR_fetchAllSortedBy:nil ascending:YES withPredicate:nil groupBy:nil delegate:self inContext:self.managedObjectContext];
}
return _fetchedResultsController;
}
#pragma mark - Table View Data Source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [[self.fetchedResultsController.sections[0]objects] count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSString *string = [[[self.fetchedResultsController.sections[0]objects]objectAtIndex:section]title];
return string;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[[[[self.fetchedResultsController.sections[0]objects]objectAtIndex:section]users] allObjects] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"cell_identifier";
[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellIdentifier];
TableViewCell *cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
UserProfile *user = [[[[[self.fetchedResultsController.sections[0] objects]objectAtIndex:indexPath.section] users] allObjects]objectAtIndex:indexPath.row];
cell.textLabel.text = user.title;
cell.detailTextLabel.text = user.email;
return cell;
}
我想如果你用
-[self.fetchedResults objectAtIndexPath:indexPath]
您将大大减少已有的数据访问代码
另外,不要这样做:
[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellIdentifier];
在tableView中:cellforrowatinexpath:method。通常,在viewDidLoad:或其他一些初始化方法中执行此操作
而且,我个人会使用-[NSArray lastObject]或-[NSArray firstObject]方法。如果数组中没有对象,这些方法将返回nil,而不是因为数组索引越界异常而崩溃