2013-12-10 81 views
1

在我的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 
+4

使用自定义委托来传递数据。并在自定义代表重新加载您的表查看数据.... – Seeker

+0

@ mvasco-重新加载视图将出现 –

+0

谢谢@Seeker,但你可以更清楚你的建议? – mvasco

回答

3

的代码重新加载您在viewWillAppear中的tableview。

-(void)viewWillAppear:(BOOL)animated 
{ 


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

的评论谢谢@ user203108,它已经按照你所说的完成了,并且tableview没有更新,我想我必须更新fetch请求而不是tableview本身。 – mvasco

+0

@ mvasco:查看我更新的答案。 – user203108

+0

也就是说,谢谢@ user203108 .....它现在在工作......你很棒。 – mvasco

1

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

否则你不需要使用NSFetchedResultsController。有关在addVC实施NSFetchedResultsController代表please see this link.

+0

谢谢@bbarnhart,但我已经接受user203108的答案。 – mvasco

1

声明此自定义委托在addVC

@protocol AddViewControllerDelegate <NSObject> 

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

@end 

,并宣布自定义委托物业可变信息

@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]; 
} 
+0

谢谢@TamilKing,但我接受了另一个答案... – mvasco