从另一个视图重新加载表视图

时间:2013-12-10 04:24:45

标签: ios uitableview core-data

在我的iOS应用中,我需要从另一个视图更新tableview。我尝试过使用NSNotifications但没有成功。第一个视图包含一个使用获取请求从核心数据填充的tableview。此视图还有一个Add按钮,用于打开视图以将对象添加到核心数据实体。此第二个视图有几个文本字段,一个保存按钮和一个后退按钮,可以再次打开第一个视图,但行不会更新。 这是第一个视图控制器的代码:

#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{
    [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

这是第二个视图控制器的代码

#import "AddToDoViewController.h"

#import "FavoriteThing.h"
#import "AppDelegate.h"
#import "RootViewController.h"

@interface AddToDoViewController ()

@end

@implementation AddToDoViewController
@synthesize ToDoDescriptionTextField,ToDoTextField,fetchedResultsController;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [ToDoTextField becomeFirstResponder];



    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

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



- (IBAction)BackButtonAction:(id)sender {

     [self dismissModalViewControllerAnimated:YES];
}


- (IBAction)SaveButtonAction:(id)sender {


    AppDelegate* appDelegate = [AppDelegate sharedAppDelegate];
    NSManagedObjectContext* context = appDelegate.managedObjectContext;

    NSManagedObject *favoriteThing = [NSEntityDescription insertNewObjectForEntityForName:@"FavoriteThing" inManagedObjectContext:context];


    [favoriteThing setValue:@"ToDo 000250" forKey:@"thingName"];
    [favoriteThing setValue:@"It sold out in eight days this year, you know?" forKey:@"thingDescription"];
    [favoriteThing setValue:[NSNumber numberWithInt:0] forKey:@"displayOrder"];




    NSError *error;
    if(! [context save:&error])
    {
        NSLog(@"Whoopw,couldn't save:%@", [error localizedDescription]);
    }
                               }
@end

3 个答案:

答案 0 :(得分:1)

在viewWillAppear中重新加载您的tableview。

-(void)viewWillAppear:(BOOL)animated
{


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

答案 1 :(得分:1)

由于您使用的是NSFetchedResultsController,因此您应该使用它的委托更新您的表。

否则您不需要使用NSFetchedResultsController。有关实现NSFetchedResultsController委托please see this link.

的信息

答案 2 :(得分:1)

在addVC中声明此自定义委托

@protocol AddViewControllerDelegate <NSObject>

-(void)AddPhotoViewController:(AddViewController *)addViewController store:(NSString *) data;

@end

并在addVC中将自定义委托声明为属性变量

@property(strong, nonatomic) id <AddViewControllerDelegate> delegate;

在mainVC中执行此操作

addVC 这样

AddPhotoViewController*   addVC = [[AddPhotoViewController alloc]init];
addVC.delegate = self;
[self.navigationController pushViewController:addVC animated:YES];


-(void)AddPhotoViewController:(AddPhotoViewController *)addViewController store:(NSString *)data
{
    [table_array addObject:data];
    [self.tableView reloadData];
}
相关问题