0

我有一个带有核心数据项目的情节提要,其中包含 1 个名为“Password”的实体和 4 个字符串属性,数据通过 fecthedResultsController 连接到表视图,并且这些部分由称为“type”的属性之一设置。

当我启动我的应用程序时,一切正常,我可以添加、更新和删除,没有任何问题。即使当我离开应用程序进入主屏幕并返回时,也没有任何反应。问题是当我从多任务菜单关闭应用程序并重新启动它时,我会在相同数量的好单元格中得到空单元格。它们被分组在顶部,没有部分。

我究竟做错了什么?

插入视图控制器.m

-(IBAction)insertPassword:(id)sender
{
    NSInteger row;
    NSString*subTypeSelectd=[[NSString alloc]init];

    row = [pickerSubjects selectedRowInComponent:0];
    subTypeSelectd = [arrSubSubjects objectAtIndex:row];

    NSInteger row2;
    NSString*TypeSelectd=[[NSString alloc]init];

    row2 = [pickerSubjects selectedRowInComponent:1];
    TypeSelectd = [arrSubject objectAtIndex:row2];

//    self.insertPassword.desc=self.txtDesc.text;
//    self.insertPassword.userName=self.txtUserName.text;
//    self.insertPassword.password=self.txtPassword.text;
//    self.insertPassword.type=TypeSelectd;
//    self.insertPassword.subType=subTypeSelectd;
//    NSLog(@"insertPassword");
//    [self.delegete addPasswordViewControllerDidSave];

    AppDelegate *delegate = [UIApplication sharedApplication].delegate;
    NSManagedObjectContext *addViewcontrollerLocalContext = delegate.managedObjectContext;

    NSManagedObject*password=[NSEntityDescription insertNewObjectForEntityForName:@"Password" inManagedObjectContext:addViewcontrollerLocalContext];


    [password setValue:self.txtDesc.text forKey:@"desc"];
    [password setValue:self.txtUserName.text forKey:@"userName"];
    [password setValue:self.txtPassword.text forKey:@"password"];
    [password setValue:subTypeSelectd forKey:@"subType"];
    [password setValue:TypeSelectd forKey:@"type"];

    NSError*error;
    if(![addViewcontrollerLocalContext save:&error])
        NSLog(@"input %@",error);
    else NSLog(@"saved");

    [self.navigationController popViewControllerAnimated:YES]; 
}

和 mainViewController.m

-(void)addPasswordViewControllerDidSave
{
    NSManagedObjectContext*context=self.manageObjectContext;
    NSError*error;
    if(![context save:&error])
        NSLog(@"error : %@",error);

    NSLog(@"addPasswordViewControllerDidSave");

    [self.navigationController popViewControllerAnimated:YES];
}
-(void)addPasswordViewControllerDidDelete:(Password *)passwordToDelete
{
    NSLog(@"B");

    NSManagedObjectContext*context=self.manageObjectContext;
    [context deleteObject:passwordToDelete];
    [self.navigationController popViewControllerAnimated:YES];

}


-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if([[segue identifier]isEqualToString:@"addPassword"])
    {
        insertViewController*ipvc=(insertViewController*)[segue destinationViewController];

        Password*p=(Password*)[NSEntityDescription insertNewObjectForEntityForName:@"Password" inManagedObjectContext:[self manageObjectContext]];
//        ipvc.delegete=self;
        ipvc.insertPassword=p;

    }
    if([[segue identifier]isEqualToString:@"updatePassword"])
    {
        updateViewController*uvc=(updateViewController*)[segue destinationViewController];

        NSIndexPath*indexPath=[self.tableView indexPathForSelectedRow];
        Password*p=[self.fecthedResultsController objectAtIndexPath:indexPath];
        uvc.updatePassword=p;
    }

}

//-------------------------------------------------------------table------------
-(NSFetchedResultsController*)fecthedResultsController
{
    if(fecthedResultsController!=nil)
        return fecthedResultsController;
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Password"
                                              inManagedObjectContext:[self manageObjectContext]];
    [fetchRequest setEntity:entity];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"type" ascending:YES];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
    [fetchRequest setSortDescriptors:sortDescriptors];
    fecthedResultsController=[[NSFetchedResultsController
                               alloc]initWithFetchRequest:fetchRequest managedObjectContext:[self manageObjectContext]
                              sectionNameKeyPath:@"type" cacheName:nil];
    fecthedResultsController.delegate=self;
    return fecthedResultsController;
}
-(void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
    [self.tableView beginUpdates];
    [self.tableView reloadData];
}

-(void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
    [self.tableView endUpdates];
}
-(void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
      atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
     newIndexPath:(NSIndexPath *)newIndexPath
{
    UITableView*tableview=self.tableView;
    switch (type) {
        case NSFetchedResultsChangeInsert:
            [tableview insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]
                             withRowAnimation:UITableViewRowAnimationFade];
            break;
        case NSFetchedResultsChangeDelete:[tableview deleteRowsAtIndexPaths:[NSArray
                                                                             arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;
        case NSFetchedResultsChangeUpdate:{
            Password*p=[self.fecthedResultsController objectAtIndexPath:indexPath];
            UITableViewCell*cell=[tableview cellForRowAtIndexPath:indexPath];
            cell.textLabel.text=p.userName;
            cell.detailTextLabel.text=p.password;
//            cell.imageView.image=[UIImage imageWithData: p.photodata];
        }
            break;
        case NSFetchedResultsChangeMove:
            [tableview deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                             withRowAnimation:UITableViewRowAnimationFade];
            [tableview insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]
                             withRowAnimation:UITableViewRowAnimationFade];
            break;
        default:
        break; }}

-(void)controller:(NSFetchedResultsController *)controller didChangeSection:
(id<NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:
(NSFetchedResultsChangeType)type
{
    switch (type) {
        case NSFetchedResultsChangeInsert:
            [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex]
                          withRowAnimation:UITableViewRowAnimationFade];
            break;
        case NSFetchedResultsChangeDelete:[self.tableView deleteSections:[NSIndexSet
                                                                          indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
        default:
            break;
    } }

-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:
(NSInteger)section
{
    return [[[self.fecthedResultsController sections]objectAtIndex:section]name];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:
(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSManagedObjectContext*context=[self manageObjectContext];
        Password*passwordToDelete=[self.fecthedResultsController objectAtIndexPath:indexPath];
        [context deleteObject:passwordToDelete];
        NSError*error;
        if(![context save:&error])
            NSLog(@"error");

            } }

//-------------------------------------------------------------table-end-----------

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)viewWillApear
{

}
- (void)viewDidLoad
{
    [super viewDidLoad];

    NSError*error;
    if(![[self fecthedResultsController]performFetch:&error])
    {
        NSLog(@"ERROR");
        abort();
    }


    // Uncomment the following line to preserve selection between presentations.
//    self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//#warning Potentially incomplete method implementation.
    // Return the number of sections.
    NSLog(@"%i",[[self.fecthedResultsController sections]count]);
    return [[self.fecthedResultsController sections]count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//#warning Incomplete method implementation.
    // Return the number of rows in the section.
    id<NSFetchedResultsSectionInfo>secInfo=[[self.fecthedResultsController
                                             sections]objectAtIndex:section];
    return [secInfo numberOfObjects];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    // Configure the cell...
    NSLog(@"cell");
    Password*p=[self.fecthedResultsController objectAtIndexPath:indexPath];
    cell.textLabel.text=p.userName;
    cell.detailTextLabel.text=p.password;
//    if(p.photodata!=nil)
//        cell.imageView.image=[UIImage imageWithData: p.photodata];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}
4

1 回答 1

0

您的cellForRowAtIndexPath方法中的这一行有错字:

它应该被获取ResultsController:

Password*p=[self.fecthedResultsController objectAtIndexPath:indexPath];

并再次在您的numberOfSectionInTableView

NSLog(@"%i",[[self.fecthedResultsController sections]count]);
return [[self.fecthedResultsController sections]count];

可能还有其他方法。

于 2013-05-05T22:39:52.913 回答