Source

sage-iphone-app / Classes / RootViewController.m

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
//
//  RootViewController.m
//  iSage
//
//  Created by Ivan Andrus on 4/29/11.
//  Copyright 2011 Ivan Andrus. All rights reserved.
//

#import "RootViewController.h"
#import "AlephCell.h"
#import <UIKit/UITableView.h>


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


@implementation RootViewController

@synthesize fetchedResultsController=fetchedResultsController_, managedObjectContext=managedObjectContext_;

#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];
    resultsColor      = [[UIColor colorWithRed:0.5  green:0.5  blue:0.5  alpha:1.0] retain];
    staleResultsColor = [[UIColor colorWithRed:0.75 green:0.25 blue:0.25 alpha:1.0] retain];
    backgroundEditViews = [[NSMutableDictionary dictionaryWithCapacity:5] retain];

    // Create an Info button
    UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
    [infoButton addTarget:self action:@selector(showInfo:) forControlEvents:UIControlEventTouchUpInside];
    infoButton.frame=CGRectMake(0.0, 100.0, 50.0, 30.0);

    UIBarButtonItem *infoBarButton = [[UIBarButtonItem alloc] initWithCustomView:infoButton];
    self.navigationItem.leftBarButtonItem = [infoBarButton autorelease];


    // Create an Add button
    UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
                                                                               target:self
                                                                               action:@selector(insertNewObject)];
    self.navigationItem.rightBarButtonItem = [addButton autorelease];
    // TODO: maybe change so that touching the title gives info
    // That seems like it might be cleaner:
    // http://www.iphonedevsdk.com/forum/iphone-sdk-development/9521-click-navigationbar-title-perform-action.html

    // TODO: custom accessory view
    // http://www.edumobile.org/iphone/iphone-programming-tutorials/impliment-a-custom-accessory-view-for-your-uitableview-in-iphone/
}


// Implement viewWillAppear: to do additional setup before the view is presented.
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

-(void)didUpdateWithJSON:(NSNotification*)notification{
    // NSLog(@"didUpdateWithJSON");
    [self.tableView reloadData];
}

- (IBAction)showInfo:(id)sender {

    FlipsideViewController *controller = [[FlipsideViewController alloc] initWithNibName:@"FlipsideView" bundle:nil];
    controller.delegate = self;

    controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentModalViewController:controller animated:YES];

    [controller release];
}

- (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller {

    [self dismissModalViewControllerAnimated:YES];
}


- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {

    NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
    if ( ![managedObject isKindOfClass:[AlephCell class]] ) {
        NSLog(@"Something really weird happened");
        return;
    }
    AlephCell * alephCell = (AlephCell*) managedObject;

    // Empty cells
    if ([alephCell.input isEqualToString:@""]) {
        cell.textLabel.text = @"Tap to edit...";
        cell.textLabel.textColor = staleResultsColor;
    } else {
        cell.textLabel.text = alephCell.input.description;
        cell.textLabel.textColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0];
    }

    if ( alephCell.output != nil ) {
        // It doesn't display trailing newlines well, so trim them.
        // This has the unfortunate side effect of trimming newlines off the begining as well.
        cell.detailTextLabel.text = [alephCell.output.description
                                     stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
    } else {
        cell.detailTextLabel.text = @"";
    }

    if ( alephCell.image ) {
        // TODO: move this to where I store the image
        // For some reason scaling it myself first makes it look much nicer
        UIImage * image = [UIImage imageWithData:alephCell.image];
        CGSize size = CGSizeMake(70.f, 70.0f);
        UIGraphicsBeginImageContext(size);
        [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
        UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        cell.imageView.image = scaledImage;
    } else {
        // In case it's reused from one that had an image
        // TODO: perhaps we should use a different cell cache for those with images...
        cell.imageView.image = nil;
    }

    if ( [alephCell isWorking] ) {
        UIActivityIndicatorView * spinner = [[UIActivityIndicatorView alloc]
                                             initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [spinner startAnimating];
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                    action:@selector(spinnerTapped:)];

        [spinner addGestureRecognizer:singleTap];
        cell.accessoryView = spinner;

        [spinner release];
        [singleTap release];

        // The data is stale, so indicate that
        cell.detailTextLabel.textColor = staleResultsColor;

    } else {

        // The data is not stale, so indicate that
        cell.detailTextLabel.textColor = resultsColor;

        // TODO: my own caching of these images?
        // TODO: should probably cache the buttons instead -- didn't seem to work, maybe you can only use a button once
        // TODO: How to make icons:
        // http://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/MobileHIG/IconsImages/IconsImages.html%23//apple_ref/doc/uid/TP40006556-CH14-SW1
        // http://mathiasbynens.be/notes/touch-icons -- this is about icons for web apps
        UIImage *image;
        switch ( [[alephCell valueForKey:@"status"] intValue] ) {

            case AlephCellStatusHasOutput:
                // NSLog(@"okay");
                image = [UIImage imageNamed:@"okay"];
                break;

            case AlephCellStatusSyntaxError:
                // NSLog(@"syntaxError");
                image = [UIImage imageNamed:@"syntaxError"];
                break;

            case AlephCellStatusJSONParseError:
            case AlephCellStatusNetworkError:
                // NSLog(@"networkError");
                image = [UIImage imageNamed:@"networkError"];
                break;

            case AlephCellStatusHasInput:
            case AlephCellStatusHasAlephID:
                // We should be working in these two situations, so if
                // we're not then it's invalid
            case AlephCellStatusUninitialized:
            default:

                // NSLog(@"invalid:%@",[alephCell valueForKey:@"status"]);
                image = [UIImage imageNamed:@"invalid"];
                break;
        }

        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        CGRect frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
        button.frame = frame;
        [button setBackgroundImage:image forState:UIControlStateNormal];

        [button addTarget:self action:@selector(accessoryButtonTapped:event:)  forControlEvents:UIControlEventTouchUpInside];
        button.backgroundColor = [UIColor clearColor];
        cell.accessoryView = button;
    }
}

- (void) accessoryButtonTapped:(id)sender event:(id)event{

    NSSet *touches = [event allTouches];
    UITouch *touch = [touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition];
    if (indexPath != nil) {
        [self tableView:self.tableView accessoryButtonTappedForRowWithIndexPath: indexPath];
    }
}

- (void) spinnerTapped:(UIGestureRecognizer *)gestureRecognizer {
    CGPoint currentTouchPosition = [gestureRecognizer locationInView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition];
    if (indexPath != nil) {
        [self tableView:self.tableView accessoryButtonTappedForRowWithIndexPath: indexPath];
    }
}

- (BOOL)canBecomeFirstResponder {
    return YES;
}

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

    // NSLog(@"Accessory button tapped");
    NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
    if ( ![managedObject isKindOfClass:[AlephCell class]] ) {
        NSLog(@"Something really weird happened.");
        return;
    }
    AlephCell * alephCell = (AlephCell*) managedObject;

    if ( [alephCell isWorking] ) {
        // They tapped on the spinner
        NSLog(@"Requesting cancelled");
        NSString * message = [NSString stringWithFormat:@"The computation is currently running.  You can terminate it if you wish."];

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Cancel request"
                                                        message:message
                                                       delegate:self
                                              cancelButtonTitle:@"Continue"
                                              otherButtonTitles:@"Terminate", nil];
        [alert show];
        copyAlephCell = [alephCell retain];
        [alert release];
        return;
    }

    switch ([alephCell.status intValue]) {
        case AlephCellStatusSyntaxError: // We may want to copy/email a syntax error to debug it.
        case AlephCellStatusHasOutput: {

            UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
            [[self shareButtonDelegate] displayShareSheet:self
                                                  forCell:alephCell
                                               fromWhence:cell.accessoryView];
            break;
        }
        case AlephCellStatusNetworkError: {
            NSLog(@"NetworkError retried");
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Network Error"
                                                            message:@"Not sure what happened."//[[requestManager networkError] localizedDescription]
                                                           delegate:self
                                                  cancelButtonTitle:@"Fine, whatever"
                                                  otherButtonTitles:@"Retry", nil];
            copyAlephCell = [alephCell retain];
            [alert show];
            [alert release];
            break;
        }
        case AlephCellStatusJSONParseError: {
            NSLog(@"JSONParseError error retried");
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Server Response Error"
                                                            message:@"I was unable to understand the response from the server"
                                                           delegate:self
                                                  cancelButtonTitle:@"Fine, whatever"
                                                  otherButtonTitles:@"Retry", nil];
            copyAlephCell = [alephCell retain];
            [alert show];
            [alert release];
            break;
        }
        case AlephCellStatusUninitialized:
        default:
            NSLog(@"AlephCellStatusUninitialized:%@",alephCell.status);
            break;
    }
}


#pragma mark -
#pragma mark Add a new object

- (void)insertNewObject {
    [self insertNewObjectWithString:@""];
}

- (void)newCellWithDefault:(id)initial_value {
    [self insertNewObjectWithString:initial_value];
}

- (void)insertNewObjectWithString:(id)initial_value {

    // Create a new instance of the entity managed by the fetched results controller.
    NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
    NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
    NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];

    // If appropriate, configure the new managed object.
    [newManagedObject setValue:[NSDate date] forKey:@"creation_time"];
    [newManagedObject setValue:nil forKey:@"image"];
    [newManagedObject setValue:[NSNumber numberWithInt:AlephCellStatusUninitialized] forKey:@"status"];
    if ( [initial_value isKindOfClass:[NSString class]] ) {
        [newManagedObject setValue:initial_value forKey:@"input"];
    } else {
        [newManagedObject setValue:@"" forKey:@"input"];
    }

    // Save the context.
    NSError *error = nil;
    if (![context save:&error]) {
        /*
         Replace this implementation with code to handle the error appropriately.

         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.
         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    [self editAlephCell:newManagedObject];
}

- (void)setEditing:(BOOL)editing animated:(BOOL)animated {

    // Prevent new objects being added when in editing mode.
    [super setEditing:(BOOL)editing animated:(BOOL)animated];
    self.navigationItem.rightBarButtonItem.enabled = !editing;
}


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


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


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"AlephCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell.
    [self configureCell:cell atIndexPath:indexPath];

    return cell;
}


// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the managed object for the given index path
        NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
        [context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]];

        // Save the context.
        NSError *error = nil;
        if (![context save:&error]) {
            /*
             Replace this implementation with code to handle the error appropriately.

             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.
             */
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}


- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // The table view should not be re-orderable.
    return NO;
}


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSManagedObject *selectedObject = [[self fetchedResultsController] objectAtIndexPath:indexPath];
    [self editAlephCell:selectedObject];
}


-(void)editAlephCell:(NSManagedObject*)selectedObject{

    NSValue *p = [backgroundEditViews objectForKey:[NSValue valueWithPointer:selectedObject]];
    EditViewController *detailViewController =
        p ? [(EditViewController *)[p pointerValue] retain]
          : [[EditViewController alloc] initWithNibName:@"EditView" bundle:nil];

    // Pass the selected object to the new view controller.
    [detailViewController setSelectedObject:selectedObject];

    detailViewController.delegate = self;

    // Display the new view
    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];

}


- (void)editViewControllerDidFinish:(EditViewController *)controller nextDefault:(NSString*)str {
    // The only time this is called is when we want to add a new one
    [self insertNewObjectWithString:str];
}

- (void)saveEditViewForBackground:(EditViewController*)controller {

    NSValue *key = [NSValue valueWithPointer:controller.selectedObject];
    switch ( [[controller.selectedObject valueForKey:@"status"] intValue] ) {
        case AlephCellStatusHasOutput:
        case AlephCellStatusSyntaxError:
        case AlephCellStatusHasInput:
        case AlephCellStatusJSONParseError:
        case AlephCellStatusNetworkError:

        case AlephCellStatusUninitialized:
            NSValue* pointer = [backgroundEditViews objectForKey:key];
            if (pointer) {
                NSManagedObject *sel = [pointer pointerValue];
                [sel release];
            }
            [backgroundEditViews removeObjectForKey:key];
            break;

        case AlephCellStatusHasAlephID:
        default:
            [backgroundEditViews setObject:[NSValue valueWithPointer:[controller retain]]
                                    forKey:key];
            break;
    }
}

#pragma mark -
#pragma mark - shareButtonDelegate

- (ShareButtonDelegate*)shareButtonDelegate
{
    if (!shareButtonDelegate) {
        shareButtonDelegate = [[ShareButtonDelegate alloc] init];
    }
    return shareButtonDelegate;
}


#pragma mark -
#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    // NSLog(@"button at index %d",buttonIndex);
    if (copyAlephCell != nil && buttonIndex != [alertView cancelButtonIndex]) {
        // NSLog(@"button named: %@",[alertView buttonTitleAtIndex:buttonIndex]);
        if ( [[alertView buttonTitleAtIndex:buttonIndex] isEqual:@"Terminate"] ) {
            // NSLog(@"Cancelling request");
            NSValue* pointer = [backgroundEditViews objectForKey:[NSValue valueWithPointer:copyAlephCell]];
            if (pointer) {
                NSManagedObject *sel = [pointer pointerValue];
                [sel release];
            }
            [backgroundEditViews removeObjectForKey:[NSValue valueWithPointer:copyAlephCell]];
            copyAlephCell.isWorking = NO;
            copyAlephCell.status = [NSNumber numberWithInt:AlephCellStatusHasInput];
            [self.tableView reloadData];

        } else {
            // TODO: I think this branch isn't used currently
            // NSLog(@"clearing error");
            copyAlephCell.status = [NSNumber numberWithInt:AlephCellStatusHasInput];
            [copyAlephCell clearError];
            // redisplaying the row causes it to also be requested
            [self.tableView reloadData];
        }
    }
    [copyAlephCell release];
    copyAlephCell = nil;
}

#pragma mark -
#pragma mark Fetched results controller

- (NSFetchedResultsController *)fetchedResultsController {

    if (fetchedResultsController_ != nil) {
        return fetchedResultsController_;
    }

    // Set up the fetched results controller.
    // Create the fetch request for the entity.
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    // Edit the entity name as appropriate.
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"AlephCell" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];

    // Set the batch size to a suitable number.
    [fetchRequest setFetchBatchSize:20];

    // Edit the sort key as appropriate.
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"creation_time" ascending:NO];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];

    [fetchRequest setSortDescriptors:sortDescriptors];

    // Edit the section name key path and cache name if appropriate.
    // nil for section name key path means "no sections".
    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"];
    aFetchedResultsController.delegate = self;
    self.fetchedResultsController = aFetchedResultsController;

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

    NSError *error = nil;
    if (![fetchedResultsController_ performFetch:&error]) {
        /*
         Replace this implementation with code to handle the error appropriately.

         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.
         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return fetchedResultsController_;
}


#pragma mark -
#pragma mark Fetched results controller delegate


- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
    [self.tableView beginUpdates];
}


- (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];
            break;
    }
}


- (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:
            [self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
            break;

        case NSFetchedResultsChangeMove:
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
            [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]withRowAnimation:UITableViewRowAnimationFade];
            break;
    }
}


- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
    [self.tableView endUpdates];
}
// Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed.


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    // Relinquish ownership any cached data, images, etc that aren't in use.
}


- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)dealloc {
    [fetchedResultsController_ release];
    [managedObjectContext_ release];
    [resultsColor release];
    [staleResultsColor release];
    [shareButtonDelegate release];
    [backgroundEditViews release];

    [super dealloc];
}


@end