使用核心数据从表视图中打开编辑视图控制器

时间:2013-12-11 17:30:10

标签: ios uitableview core-data uiviewcontroller

在我的iOS应用程序中,我使用Core Data在表格视图上显示数据。在同一视图中,我添加了一个添加按钮,用于打开一个新的视图控制器,我可以在其中添加新记录。

从此视图中,我返回到表视图,并正确显示新添加的记录。现在,我想要做的是在表视图上选择一行并打开一个新的视图控制器来编辑记录的字段。编辑视图控制器名称为EditViewController。这是我的表视图控制器源,所以你可以请解释我实现的方法将选定的行记录传递给编辑视图控制器,这样我以后可以编辑和保存信息。 我已经看到了关于didSelectedRowAtIndexPath方法的问题的一些示例,但都是基于故事板,我没有在我的项目中使用。

#import "RootViewController.h"
#import "AddToDoViewController.h"


@interface RootViewController ()
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath;
@end


@implementation RootViewController

@synthesize fetchedResultsController, managedObjectContext,AddToDoButton;


#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad {
  [super viewDidLoad];
  [self setTitle:@"Today"];
  [[self navigationItem] setRightBarButtonItem:[self editButtonItem]];





  NSError *error = nil;
  if (![[self fetchedResultsController] performFetch:&error])
  {
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
  }
}
- (void) viewWillAppear:(BOOL)animated{
    NSError *error = nil;
    if (![[self fetchedResultsController] performFetch:&error])
    {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    [self.tableView reloadData];
}
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
  NSManagedObject *managedObject = [fetchedResultsController objectAtIndexPath:indexPath];
  [[cell textLabel] setText:[[managedObject valueForKey:@"thingName"] description]];
  [[cell detailTextLabel] setText:[[managedObject valueForKey:@"thingDescription"] description]];
  [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    cell.textLabel.textColor = [UIColor blueColor];
    cell.textLabel.font = [UIFont fontWithName:@"Noteworthy" size:16.0f];
    cell.detailTextLabel.font = [UIFont fontWithName:@"Noteworthy" size:14.0f];
}

#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
  return [[fetchedResultsController sections] count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
  id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
  return [sectionInfo numberOfObjects];
}

- (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:@"Cell"] autorelease];
  }

  [self configureCell:cell atIndexPath:indexPath];

  return cell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
  if (editingStyle == UITableViewCellEditingStyleDelete)
  {
    NSManagedObjectContext *context = [fetchedResultsController managedObjectContext];
    [context deleteObject:[fetchedResultsController objectAtIndexPath:indexPath]];

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

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
  return YES;
}

- (void)tableView:(UITableView *)tableView 
moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath 
      toIndexPath:(NSIndexPath *)destinationIndexPath;
{  
  NSMutableArray *things = [[fetchedResultsController fetchedObjects] mutableCopy];

  // Grab the item we're moving.
  NSManagedObject *thing = [[self fetchedResultsController] objectAtIndexPath:sourceIndexPath];

  // Remove the object we're moving from the array.
  [things removeObject:thing];
  // Now re-insert it at the destination.
  [things insertObject:thing atIndex:[destinationIndexPath row]];

  // All of the objects are now in their correct order. Update each
  // object's displayOrder field by iterating through the array.
  int i = 0;
  for (NSManagedObject *mo in things)
  {
    [mo setValue:[NSNumber numberWithInt:i++] forKey:@"displayOrder"];
  }

  [things release], things = nil;

  [managedObjectContext save:nil];
}






#pragma mark -
#pragma mark Fetched results controller
- (IBAction)AddToDoAction:(id)sender {

    AddToDoViewController *viewController = [[AddToDoViewController alloc] init];
    [self presentViewController:viewController animated:YES completion:nil];

}

- (NSFetchedResultsController *)fetchedResultsController
{
  if (fetchedResultsController) return fetchedResultsController;

  NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
  NSEntityDescription *entity = 
               [NSEntityDescription entityForName:@"FavoriteThing" 
                           inManagedObjectContext:managedObjectContext];

  [fetchRequest setEntity:entity];

  NSSortDescriptor *sortDescriptor = 
              [[NSSortDescriptor alloc] initWithKey:@"displayOrder" 
                                          ascending:YES];

  NSArray *sortDescriptors = [[NSArray alloc] 
                              initWithObjects:sortDescriptor, nil];  
  [fetchRequest setSortDescriptors:sortDescriptors];

  NSFetchedResultsController *aFetchedResultsController = 
              [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest 
                                                  managedObjectContext:managedObjectContext
                                                    sectionNameKeyPath:nil cacheName:@"ThingsCache"];
  aFetchedResultsController.delegate = self;
  [self setFetchedResultsController:aFetchedResultsController];

  [aFetchedResultsController release];
  [fetchRequest release];
  [sortDescriptor release];
  [sortDescriptors release];

  return fetchedResultsController;
}    

- (void)dealloc {
  [fetchedResultsController release];
  [managedObjectContext release];


  [super dealloc];
}


@end

你好。我在@flexaddicted回答之后做了以下事情: 我已将以下代码添加到接口块的EditToDoViewController.h文件中:

NSManagedObject *selectedObject;

并遵循声明:

@property (nonatomic, retain) NSManagedObject *selectedObject;

在我的EditToDoViewController.m文件中,我添加了以下代码:

@synthesize selectedObject;

didSelectRowAtIndexPath方法更改为:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {


    EditToDoViewController *detailViewController = [[EditToDoViewController alloc] initWithNibName:@"EditToDoViewController" bundle:nil];
    NSManagedObject *selectedObject = [[self fetchedResultsController] objectAtIndexPath:indexPath];
    EditToDoViewController.selectedObject = selectedObject;

}

但此时我收到此错误消息:  在'EditToDoViewController'

类型的对象上找不到属性'selectedObject'

我想我已经很好地声明了属性'selectedObject',我不明白错误.... 谢谢

1 个答案:

答案 0 :(得分:1)

第1步

UITableView实施正确的委托方法,即UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // do something here (see Step 2 and 3)
}

第2步

检索正确的项目。

NSManagedObject *mo = [yourResultsController objectAtIndexPath:indexPath];

第3步

呈现模态控制器传递数据。另一种方法是将您正在使用的控制器包装在UINavigationController中并按下新控制器。例。

 YourAdditionalViewController *ac = [[YourAdditionalViewController alloc] init];
 ac.setMo = mo; // as a property or passed to a custom init method of YourAdditionalController
 [self presentViewController:ac animated:YES completion: nil];

所以回顾一下。

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSManagedObject *mo = [yourResultsController objectAtIndexPath:indexPath];

    YourAdditionalViewController *ac = [[YourAdditionalViewController alloc] init];
    ac.setMo = mo; // as a property or passed to a custom init method of YourAdditionalController
    [self presentViewController:ac animated:YES completion: nil];
}

如果我需要改进答案,请告诉我。

P.S。检查代码,因为我写的没有Xcode支持。