ios/coredata/nfetchresultscontroller。在添加新记录后,如何获取要更新的记录表视图

ios/coredata/nfetchresultscontroller。在添加新记录后,如何获取要更新的记录表视图,ios,nsfetchedresultscontroller,Ios,Nsfetchedresultscontroller,我试图使用委托模式在添加新记录后获取要更新的记录表视图 我在tableview控制器中有nsfetched results控制器的代码。该表作为nsfetchedresults控制器的委托订阅。我在添加新记录控制器中有保存代码。我做错了什么?多谢各位 table view controller: header: @interface IDTVC : UITableViewController<UITableViewDataSource, UITableViewDelegate,NSFetc

我试图使用委托模式在添加新记录后获取要更新的记录表视图

我在tableview控制器中有nsfetched results控制器的代码。该表作为nsfetchedresults控制器的委托订阅。我在添加新记录控制器中有保存代码。我做错了什么?多谢各位

table view controller:
header:
@interface IDTVC : UITableViewController<UITableViewDataSource, UITableViewDelegate,NSFetchedResultsControllerDelegate>

source:
#pragma mark - Fetched Results Controller

-(NSFetchedResultsController *)fetchedResultsController {
    if (_fetchedResultsController==nil){
        NSFetchRequest *fetchRequest= [[NSFetchRequest alloc] init];
        //access the single managed object context through model singleton
        NSManagedObjectContext *context = [IDModel sharedInstance].managedObjectContext;
        //fetch request requires an entity description - we're only interested in IDModel managed objects
        NSEntityDescription *entity =[NSEntityDescription entityForName:@"Dare" inManagedObjectContext:context];
        fetchRequest.entity=entity;
        //we'll order the IDModel ID Model objects in name sort order
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]initWithKey:@"name" ascending:YES];
        NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor,nil];
        fetchRequest.sortDescriptors=sortDescriptors;

        self.fetchedResultsController=[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:context sectionNameKeyPath:nil cacheName:nil];
 //       self.fetchedResultsController.delegate=self;

        [self.fetchedResultsController setDelegate:self];

        NSError *error = nil;
        if (![self.fetchedResultsController performFetch:&error]) {
        NSLog(@"Unresolved error %@,%@",error,[error userInfo]);
        abort();
    }

    }
    return _fetchedResultsController;
}
//following supposed to be sufficient for delegate pattern to work
-(void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
//change
}

AddRecord Controller

- (IBAction)save:(id)sender {

    self.managedObjectContext = [IDModel sharedInstance].managedObjectContext;;
    // Helpers

    NSString *name = self.textField.text;
    NSString *sub = self.subField.text;

 //    [[[UIAlertView alloc] initWithTitle:name message:@"Your record needs a name." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
    NSLog(@"save triggered");
    if (name && name.length) {
        // Create Entity
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"newitem" inManagedObjectContext:self.managedObjectContext];

        // Initialize Record
        NSManagedObject *record = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:self.managedObjectContext];

        // Populate Record
        [record setValue:name forKey:@"name"];
        [record setValue:sub forKey:@"sub"];

     //   [record setValue:[NSDate date] forKey:@"createdAt"];

        // Save Record
        NSError *error = nil;

        if ([self.managedObjectContext save:&error]) {
            // Dismiss View Controller
            [self dismissViewControllerAnimated:YES completion:nil];
            ;


        } else {
            if (error) {
                NSLog(@"Unable to save record.");
                NSLog(@"%@, %@", error, error.localizedDescription);
            }

            // Show Alert View
            [[[UIAlertView alloc] initWithTitle:@"Warning" message:@"Your record could not be saved." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
        }

    } else {
        // Show Alert View
        [[[UIAlertView alloc] initWithTitle:@"Warning" message:@"Your item needs a name." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
    }
}
//dismiss keyboard
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    NSLog(@"touchesBegan:withEvent:");
    [self.view endEditing:YES];
    [super touchesBegan:touches withEvent:event];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"Add Item";
    [IDModel sharedInstance];

    self.managedObjectContext = self.managedObjectContext;
}
表格视图控制器:
标题:
@接口IDTVC:UITableViewController
资料来源:
#pragma标记-获取的结果控制器
-(NSFetchedResultsController*)fetchedResultsController{
if(_fetchedResultsController==nil){
NSFetchRequest*fetchRequest=[[NSFetchRequest alloc]init];
//通过模型singleton访问单个托管对象上下文
NSManagedObjectContext*上下文=[IDModel sharedInstance].managedObjectContext;
//获取请求需要实体描述-我们只对IDModel托管对象感兴趣
NSEntityDescription*实体=[NSEntityDescription entityForName:@“Dare”在托管对象上下文:上下文中];
fetchRequest.entity=实体;
//我们将按名称排序顺序对IDModel ID模型对象进行排序
NSSortDescriptor*sortDescriptor=[[NSSortDescriptor alloc]initWithKey:@“name”升序:是];
NSArray*sortDescriptors=[[NSArray alloc]initWithObjects:sortDescriptor,nil];
fetchRequest.sortDescriptors=sortDescriptors;
self.fetchedResultsController=[[NSFetchedResultsController alloc]initWithFetchRequest:FetchRequestManagedObjectContext:context sectionNameKeyPath:nil cacheName:nil];
//self.fetchedResultsController.delegate=self;
[self.fetchedResultsController设置委托:self];
n错误*错误=nil;
如果(![self.fetchedResultsController性能检测:&错误]){
NSLog(@“未解决的错误%@,%@”,错误,[error userInfo]);
中止();
}
}
返回_fetchedResultsController;
}
//以下内容应该足以让委托模式工作
-(void)controllerDidChangeContent:(NSFetchedResultsController*)控制器{
//改变
}
添加记录控制器
-(iAction)保存:(id)发件人{
self.managedObjectContext=[IDModel sharedInstance].managedObjectContext;;
//助手
NSString*name=self.textField.text;
NSString*sub=self.subField.text;
//[[[UIAlertView alloc]initWithTitle:name消息:@“您的记录需要一个名称。”委托:nil CancelButtontTitle:@“确定”其他ButtontTitles:nil]show];
NSLog(@“保存已触发”);
if(name&&name.length){
//创建实体
NSEntityDescription*实体=[NSEntityDescription entityForName:@“newitem”在managedObjectContext:self.managedObjectContext];
//初始化记录
NSManagedObject*记录=[[NSManagedObject alloc]initWithEntity:entity insertIntoManagedObjectContext:self.managedObjectContext];
//填充记录
[记录集值:name forKey:@“name”];
[记录设置值:sub-forKey:@“sub”];
//[记录设置值:[NSDate date]forKey:@“createdAt”];
//保存记录
n错误*错误=nil;
if([self.managedObjectContext保存:&错误]){
//关闭视图控制器
[自我解除视图控制器激活:是完成:无];
;
}否则{
如果(错误){
NSLog(@“无法保存记录”);
NSLog(@“%@,%@”,错误,错误。本地化描述);
}
//显示警报视图
[[[UIAlertView alloc]initWithTitle:@“警告”消息:@“无法保存您的记录”。代理:无取消按钮:@“确定”其他按钮:无]显示];
}
}否则{
//显示警报视图
[[[UIAlertView alloc]initWithTitle:@“警告”消息:@“您的项目需要一个名称。”代理:无取消按钮:@“确定”其他按钮:无]显示];
}
}
//关闭键盘
-(无效)触摸开始:(NSSet*)触摸事件:(UIEvent*)事件{
NSLog(@“touchsbegind:withEvent:”);
[自视图编辑:是];
[超级触摸开始:触摸事件:事件];
}
-(无效)viewDidLoad{
[超级视图下载];
//加载视图后执行任何其他设置。
self.title=@“添加项目”;
[IDModel sharedInstance];
self.managedObjectContext=self.managedObjectContext;
}
我是否需要[self.tableView重载数据];委托模式是否应该处理更新


将保存放入“添加视图”控制器和将nsfetchresultscontroller代码放入“表格视图”是否有问题?非常感谢您的帮助。

除了您的controllerDidChangeContent委托方法外,您还需要启动表视图更新的controllerWillChangeContent。然后在controllerDidChangeContent中,您必须结束表视图上的更新

- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
[tableView beginUpdates];
}
-(void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
[tableView endUpdates];
} 
您还需要另一个委托方法来实际处理每个更新操作。下:

-(void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath
{
 switch (type)
{
    case NSFetchedResultsChangeUpdate:
        [tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.row] withRowAnimation:UITableViewRowAnimationAutomatic];
        break;

    case NSFetchedResultsChangeInsert:
        [tableView insertSections:[NSIndexSet indexSetWithIndex:newIndexPath.row] withRowAnimation:UITableViewRowAnimationAutomatic];
        break;

    case NSFetchedResultsChangeDelete:
        [tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.row] withRowAnimation:UITableViewRowAnimationAutomatic];
        break;

    case NSFetchedResultsChangeMove:
        [tableView moveSection:indexPath.row toSection:newIndexPath.row];
        break;

    default:
        NSAssert(FALSE, @"what is this?");
        break;
}
}

好的,编辑没有通过…使用Lee的答案,但是添加第四个
FetchedResultsControllerDelegate
方法:

- (void)controller:(NSFetchedResultsController *)controller
    didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
        atIndex:(NSUInteger)sectionIndex
            forChangeType:(NSFetchedResultsChangeType)type
{
    NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:sectionIndex];

    switch(type)
    {
        case NSFetchedResultsChangeInsert:
        {
            [self.tableView insertSections:indexSet
                withRowAnimation:UITableViewRowAnimationFade];
            break;
        }
        case NSFetchedResultsChangeDelete:
        {
            [self.tableView deleteSections:indexSet
                withRowAnimation:UITableViewRowAnimationFade];
            break;
        }
        default:
        {
            [self.tableView reloadSections:indexSet
                withRowAnimation:UITableViewRowAnimationAutomatic];
            break;
        }
    }
}
-(void)控制器:(NSFetchedResultsController*)控制器
didChangeSection:(id)sectionInfo
atIndex:(整数)sectionIndex
forChangeType:(NSFetchedResultsChangeType)类型
{
NSIndexSet*indexSet=[NSIndexSet indexSetWithIndex:sectionIndex];
开关(类型)
{
案例NSFetchedResultsChangesInsert:
{
[self.tableView insertSections:indexSet
withRowAnimation:UITableViewRowAnimationFade];
打破
}
案例NSFetchedResultsChangeDelete:
{
[self.tableView删除节:索引集
withRowAnimation:UITableViewRowAnimationFade];
打破
}
违约:
{
[self.tableView重新加载节:索引集
withRowAnimation:UITableViewRowAnimationAutomatic];
布雷