Advertisement
propstm

edit/add row - objective c

Sep 3rd, 2011
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 16.38 KB | None | 0 0
  1.  
  2. #import "RootViewController.h"
  3.  
  4. @interface RootViewController ()
  5. - (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath;
  6. @end
  7.  
  8. @implementation RootViewController
  9.  
  10. @synthesize fetchedResultsController=__fetchedResultsController;
  11.  
  12. @synthesize managedObjectContext=__managedObjectContext;
  13.  
  14. - (void)viewDidLoad
  15. {
  16.     [super viewDidLoad];
  17.     // Set up the edit and add buttons.
  18.     self.navigationItem.leftBarButtonItem = self.editButtonItem;
  19.  
  20.     //UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(insertNewObject)];
  21.     //self.navigationItem.rightBarButtonItem = addButton;
  22.     //[addButton release];
  23. }
  24.  
  25. - (void)viewWillAppear:(BOOL)animated
  26. {
  27.     [super viewWillAppear:animated];
  28. }
  29.  
  30. - (void)viewDidAppear:(BOOL)animated
  31. {
  32.     [super viewDidAppear:animated];
  33. }
  34.  
  35. - (void)viewWillDisappear:(BOOL)animated
  36. {
  37.     [super viewWillDisappear:animated];
  38. }
  39.  
  40. - (void)viewDidDisappear:(BOOL)animated
  41. {
  42.     [super viewDidDisappear:animated];
  43. }
  44.  
  45. /*
  46.  // Override to allow orientations other than the default portrait orientation.
  47. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
  48.     // Return YES for supported orientations.
  49.     return (interfaceOrientation == UIInterfaceOrientationPortrait);
  50. }
  51.  */
  52.  
  53. // Customize the number of sections in the table view.
  54. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  55. {
  56.     return [[self.fetchedResultsController sections] count];
  57. }
  58.  
  59. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  60. {
  61.     id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
  62.    
  63.     NSInteger rows = [sectionInfo numberOfObjects];
  64.     if (self.editing) {
  65.         rows++;
  66.     }
  67.     return rows;
  68. }
  69.  
  70. // Customize the appearance of table view cells.
  71. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  72. {
  73.  
  74.     static NSString *CellIdentifier = @"Cell";
  75.  
  76.     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  77.  /*      if (cell == nil) {
  78.         cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
  79.     }
  80.  
  81.     // Configure the cell.
  82.     [self configureCell:cell atIndexPath:indexPath];
  83.     return cell;
  84.     */
  85.     // For the Ingredients section, if necessary create a new cell and configure it with an additional label for the amount.  Give the cell a different identifier from that used for cells in other sections so that it can be dequeued separately.
  86.     id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:0];
  87.    
  88.     NSInteger rows = [sectionInfo numberOfObjects];
  89.     NSUInteger ingredientCount = rows;
  90.         NSInteger row = indexPath.row;
  91.        
  92.     if (indexPath.row < ingredientCount) {
  93.         // If the row is within the range of the number of ingredients for the current recipe, then configure the cell to show the ingredient name and amount.
  94.         static NSString *IngredientsCellIdentifier = @"IngredientsCell";
  95.        
  96.         cell = [tableView dequeueReusableCellWithIdentifier:IngredientsCellIdentifier];
  97.        
  98.         if (cell == nil) {
  99.             // Create a cell to display an ingredient.
  100.             cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:IngredientsCellIdentifier] autorelease];
  101.             cell.accessoryType = UITableViewCellAccessoryNone;
  102.         }
  103.        
  104.        //
  105.         [self configureCell:cell atIndexPath:indexPath];
  106.     } else {
  107.         // If the row is outside the range, it's the row that was added to allow insertion (see tableView:numberOfRowsInSection:) so give it an appropriate label.
  108.         NSLog(@"--- IN ADD BUTTON PORTION ---");
  109.         static NSString *AddIngredientCellIdentifier = @"AddIngredientCell";
  110.        
  111.         cell = [tableView dequeueReusableCellWithIdentifier:AddIngredientCellIdentifier];
  112.         if (cell == nil) {
  113.             // Create a cell to display "Add Ingredient".
  114.             cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:AddIngredientCellIdentifier] autorelease];
  115.             cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  116.         }
  117.         cell.textLabel.text = @"Add Ingredient";
  118.     }
  119.  
  120.     return cell;
  121.  
  122. }
  123.  
  124.  
  125. #pragma mark -
  126. #pragma mark Editing
  127.  
  128. - (void)setEditing:(BOOL)editing animated:(BOOL)animated {
  129.     NSLog(@"in set editing");
  130.     [super setEditing:editing animated:animated];
  131.     NSLog(@"1");
  132.     [self.navigationItem setHidesBackButton:editing animated:YES];
  133.     NSLog(@"2");   
  134.    
  135.     [self.tableView beginUpdates];
  136.        NSLog(@"3");
  137.     id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:0];
  138.         NSLog(@"4");
  139.    
  140.     NSUInteger ingredientsCount = [sectionInfo numberOfObjects];
  141.         NSLog(@"5");
  142.     NSArray *ingredientsInsertIndexPath = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:ingredientsCount inSection:0]];
  143.         NSLog(@"6");
  144.     if (editing) {
  145.             NSLog(@"7");
  146.         [self.tableView insertRowsAtIndexPaths:ingredientsInsertIndexPath withRowAnimation:UITableViewRowAnimationTop];
  147.             NSLog(@"8");
  148.         //overviewTextField.placeholder = @"Overview";
  149.     } else {
  150.             NSLog(@"9");
  151.         [self.tableView deleteRowsAtIndexPaths:ingredientsInsertIndexPath withRowAnimation:UITableViewRowAnimationTop];
  152.             NSLog(@"10");
  153.         //overviewTextField.placeholder = @"";
  154.     }
  155.         NSLog(@"11");
  156.     //[self.tableView endUpdates];
  157.         NSLog(@"12");
  158.     /*
  159.      If editing is finished, save the managed object context.
  160.      */
  161.     if (!editing) {
  162.             NSLog(@"13");
  163.         NSManagedObjectContext *context = self.managedObjectContext;
  164.             NSLog(@"14");
  165.         NSError *error = nil;
  166.             NSLog(@"15");
  167.         if (![context save:&error]) {
  168.             /*
  169.              Replace this implementation with code to handle the error appropriately.
  170.              
  171.              abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
  172.              */
  173.             NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
  174.             abort();
  175.         }
  176.             NSLog(@"1");
  177.     }
  178. }
  179.  
  180.  
  181. /*
  182. // Override to support conditional editing of the table view.
  183. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  184. {
  185.     // Return NO if you do not want the specified item to be editable.
  186.     return YES;
  187. }
  188. */
  189.  
  190. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  191. {
  192.     if (editingStyle == UITableViewCellEditingStyleDelete)
  193.     {
  194.         // Delete the managed object for the given index path
  195.         NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
  196.         [context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]];
  197.        
  198.         // Save the context.
  199.         NSError *error = nil;
  200.         if (![context save:&error])
  201.         {
  202.             /*
  203.              Replace this implementation with code to handle the error appropriately.
  204.              
  205.              abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
  206.              */
  207.             NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
  208.             abort();
  209.         }
  210.     }  
  211. }
  212.  
  213. - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
  214.     NSLog(@"m14");
  215.     UITableViewCellEditingStyle style = UITableViewCellEditingStyleNone;
  216.     // Only allow editing in the ingredients section.
  217.     // In the ingredients section, the last row (row number equal to the count of ingredients) is added automatically (see tableView:cellForRowAtIndexPath:) to provide an insertion cell, so configure that cell for insertion; the other cells are configured for deletion.
  218.         // If this is the last item, it's the insertion row.
  219.     id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:0];
  220.    
  221.     NSInteger rows = [sectionInfo numberOfObjects];
  222.    
  223.         if (indexPath.row == rows) {
  224.             style = UITableViewCellEditingStyleInsert;
  225.         }
  226.         else {
  227.             style = UITableViewCellEditingStyleDelete;
  228.         }
  229.     return style;
  230. }
  231.  
  232. - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
  233.     NSLog(@"m16");
  234.     BOOL canMove = NO;
  235.     id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:0];
  236.     NSInteger rows = [sectionInfo numberOfObjects];
  237.     // Moves are only allowed within the ingredients section.  Within the ingredients section, the last row (Add Ingredient) cannot be moved.
  238.         canMove = indexPath.row != rows;
  239.  
  240.     return canMove;
  241. }
  242.  
  243. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  244. {
  245.     /*
  246.     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
  247.     // ...
  248.     // Pass the selected object to the new view controller.
  249.     [self.navigationController pushViewController:detailViewController animated:YES];
  250.     [detailViewController release];
  251.     */
  252. }
  253.  
  254. - (void)didReceiveMemoryWarning
  255. {
  256.     // Releases the view if it doesn't have a superview.
  257.     [super didReceiveMemoryWarning];
  258.    
  259.     // Relinquish ownership any cached data, images, etc that aren't in use.
  260. }
  261.  
  262. - (void)viewDidUnload
  263. {
  264.     [super viewDidUnload];
  265.  
  266.     // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
  267.     // For example: self.myOutlet = nil;
  268. }
  269.  
  270. - (void)dealloc
  271. {
  272.     [__fetchedResultsController release];
  273.     [__managedObjectContext release];
  274.     [super dealloc];
  275. }
  276.  
  277. - (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
  278. {
  279.     NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
  280.     cell.textLabel.text = [[managedObject valueForKey:@"timeStamp"] description];
  281. }
  282.  
  283. - (void)insertNewObject
  284. {
  285.     // Create a new instance of the entity managed by the fetched results controller.
  286.     NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
  287.     NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
  288.     NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
  289.    
  290.     // If appropriate, configure the new managed object.
  291.     // Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template.
  292.     [newManagedObject setValue:[NSDate date] forKey:@"timeStamp"];
  293.    
  294.     // Save the context.
  295.     NSError *error = nil;
  296.     if (![context save:&error])
  297.     {
  298.         /*
  299.          Replace this implementation with code to handle the error appropriately.
  300.          
  301.          abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
  302.          */
  303.         NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
  304.         abort();
  305.     }
  306. }
  307.  
  308. #pragma mark - Fetched results controller
  309.  
  310. - (NSFetchedResultsController *)fetchedResultsController
  311. {
  312.     if (__fetchedResultsController != nil)
  313.     {
  314.         return __fetchedResultsController;
  315.     }
  316.    
  317.     /*
  318.      Set up the fetched results controller.
  319.     */
  320.     // Create the fetch request for the entity.
  321.     NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
  322.     // Edit the entity name as appropriate.
  323.     NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:self.managedObjectContext];
  324.     [fetchRequest setEntity:entity];
  325.    
  326.     // Set the batch size to a suitable number.
  327.     [fetchRequest setFetchBatchSize:20];
  328.    
  329.     // Edit the sort key as appropriate.
  330.     NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"timeStamp" ascending:NO];
  331.     NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
  332.    
  333.     [fetchRequest setSortDescriptors:sortDescriptors];
  334.    
  335.     // Edit the section name key path and cache name if appropriate.
  336.     // nil for section name key path means "no sections".
  337.     NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"];
  338.     aFetchedResultsController.delegate = self;
  339.     self.fetchedResultsController = aFetchedResultsController;
  340.    
  341.     [aFetchedResultsController release];
  342.     [fetchRequest release];
  343.     [sortDescriptor release];
  344.     [sortDescriptors release];
  345.  
  346.     NSError *error = nil;
  347.     if (![self.fetchedResultsController performFetch:&error])
  348.         {
  349.         /*
  350.          Replace this implementation with code to handle the error appropriately.
  351.  
  352.          abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
  353.          */
  354.         NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
  355.         abort();
  356.     }
  357.    
  358.     return __fetchedResultsController;
  359. }    
  360.  
  361. #pragma mark - Fetched results controller delegate
  362.  
  363. - (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
  364. {
  365.     [self.tableView beginUpdates];
  366. }
  367.  
  368. - (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
  369.            atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
  370. {
  371.     switch(type)
  372.     {
  373.         case NSFetchedResultsChangeInsert:
  374.             [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
  375.             break;
  376.            
  377.         case NSFetchedResultsChangeDelete:
  378.             [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
  379.             break;
  380.     }
  381. }
  382.  
  383. - (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
  384.        atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
  385.       newIndexPath:(NSIndexPath *)newIndexPath
  386. {
  387.     UITableView *tableView = self.tableView;
  388.    
  389.     switch(type)
  390.     {
  391.            
  392.         case NSFetchedResultsChangeInsert:
  393.             [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
  394.             break;
  395.            
  396.         case NSFetchedResultsChangeDelete:
  397.             [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
  398.             break;
  399.            
  400.         case NSFetchedResultsChangeUpdate:
  401.             [self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
  402.             break;
  403.            
  404.         case NSFetchedResultsChangeMove:
  405.             [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
  406.             [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]withRowAnimation:UITableViewRowAnimationFade];
  407.             break;
  408.     }
  409. }
  410.  
  411. - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
  412. {
  413.     [self.tableView endUpdates];
  414. }
  415.  
  416. @end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement