/
RootViewController.m
604 lines (431 loc) · 18.4 KB
/
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
//
// RootViewController.m
// Ideas
//
// Created by Oscar Del Ben on 12/27/10.
// Copyright 2010 Dibi Store di Del Ben Oscar. All rights reserved.
//
#import "RootViewController.h"
#import "IdeaDetailViewController.h"
#import "SettingsViewController.h"
#import "MailComposerViewController.h"
#import "Idea.h"
#import "ApplicationHelper.h"
#import "FlurryAPI.h"
@interface RootViewController ()
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath;
- (void)editCurrentObject:(id)sender;
- (void)showDetailView:(Idea *)aObject newIdea:(BOOL)newIdea;
- (void)showMailView;
- (void)showSettingsView;
- (void)configureTheme;
@end
@implementation RootViewController
@synthesize fetchedResultsController=fetchedResultsController_, managedObjectContext=managedObjectContext_;
@synthesize selectedIdea;
@synthesize mailComposerViewController;
#pragma mark -
#pragma mark View lifecycle
- (void)viewDidLoad {
[super viewDidLoad];
[self updateTitle];
if (mailComposerViewController == nil) {
mailComposerViewController = [[MailComposerViewController alloc] init];
mailComposerViewController.rootViewController = self;
}
UIBarButtonItem *addButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target:self
action:@selector(insertNewObject)];
self.navigationItem.rightBarButtonItem = addButton;
[addButton release];
if (!selectedIdea) {
UIBarButtonItem *optionsButton = [[UIBarButtonItem alloc]
initWithTitle:@"Settings"
style:UIBarButtonItemStyleBordered
target:self
action:@selector(showSettingsView)];
self.navigationItem.leftBarButtonItem = optionsButton;
[optionsButton release];
}
self.tableView.backgroundColor = [UIColor clearColor]; // Display image under the view
// TODO separator color
self.tableView.separatorColor = [UIColor colorWithRed:34/255.0 green:76/255.0 blue:72/255.0 alpha:1];
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
// toolbar
if (selectedIdea) {
self.navigationController.toolbarHidden = NO;
UIBarButtonItem *flexibleSPace = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:nil
action:nil];
UIBarButtonItem *editItem = [[UIBarButtonItem alloc]
initWithImage:[UIImage imageNamed:@"187-pencil.png"]
style:UIBarButtonSystemItemReply
target:self
action:@selector(editCurrentObject:)];
UIBarButtonItem *deleteItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemTrash
target:self
action:@selector(showDeleteConfirmation:)];
UIBarButtonItem *mailItem = [[UIBarButtonItem alloc]
initWithImage:[UIImage imageNamed:@"18-envelope.png"]
style:UIBarButtonSystemItemReply
target:self
action:@selector(showMailView)];
self.toolbarItems = [NSArray arrayWithObjects:
flexibleSPace,
editItem,
flexibleSPace,
mailItem,
flexibleSPace,
deleteItem,
flexibleSPace,
nil];
[flexibleSPace release];
[editItem release];
[mailItem release];
[deleteItem release];
} else {
self.navigationController.toolbarHidden = YES;
}
[self configureTheme];
}
// Implement viewWillAppear: to do additional setup before the view is presented.
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
if (selectedIdea) {
[self.navigationController setToolbarHidden:NO animated:NO];
} else {
[self.navigationController setToolbarHidden:YES animated:YES];
}
}
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations.
// return (interfaceOrientation == UIInterfaceOrientationPortrait);
return YES;
}
#pragma mark -
#pragma mark Helper methods
- (void)updateTitle
{
NSString *countText;
if ([[self.fetchedResultsController fetchedObjects] count] > 0) {
countText = [NSString stringWithFormat:@" (%d)", [[self.fetchedResultsController fetchedObjects] count]];
} else {
countText = @"";
}
if (selectedIdea) {
self.navigationItem.title = [NSString stringWithFormat:@"%@%@",
[selectedIdea valueForKey:@"name"], countText];
} else {
self.navigationItem.title = [NSString stringWithFormat:@"Ideas%@", countText];
}
}
- (void)configureTheme
{
NSDictionary *theme = [ApplicationHelper theme];
int r = [[theme objectForKey:@"red"] intValue];
int g = [[theme objectForKey:@"green"] intValue];
int b = [[theme objectForKey:@"blue"] intValue];
// Override point for customization after application launch.
self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1];
self.navigationController.toolbar.tintColor = [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1];
UIDevice *device = [UIDevice currentDevice];
if ([device userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
if ([self.tableView respondsToSelector:@selector(backgroundView)]) {
self.tableView.backgroundView = nil;
self.tableView.backgroundView = [[[UIView alloc] init] autorelease];
self.tableView.backgroundColor = [UIColor clearColor];
}
}
self.navigationController.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:[theme objectForKey:@"background"]]];
// This should be done only when the theme changed
[self.tableView reloadData];
}
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
NSDictionary *theme = [ApplicationHelper theme];
Idea *idea = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = [idea valueForKey:@"name"];
cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:17.0];
cell.accessoryType = UIButtonTypeRoundedRect;
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.numberOfLines = 0;
cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:[theme objectForKey:@"foreground"]]];
/*
UIView *selectedView = [[[UIView alloc] init] autorelease];
selectedView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:[theme objectForKey:@"selected"]]];
cell.selectedBackgroundView = selectedView;
*/
}
- (void)showDeleteConfirmation:(id)sender
{
UIActionSheet *actionSheet = [[UIActionSheet alloc]
initWithTitle:@"Deleting this entry will also delete all of its children"
delegate:self
cancelButtonTitle:@"Cancel"
destructiveButtonTitle:@"Confirm"
otherButtonTitles:nil];
[actionSheet showFromToolbar:self.navigationController.toolbar];
[actionSheet release];
}
- (void)editCurrentObject:(id)sender
{
[self showDetailView:selectedIdea newIdea:FALSE];
}
- (void)showDetailView:(Idea *)aObject newIdea:(BOOL)newIdea
{
IdeaDetailViewController *detailViewController = [[IdeaDetailViewController alloc] initWithNibName:@"IdeaDetailViewController" bundle:nil];
detailViewController.idea = aObject;
detailViewController.delegate = self;
detailViewController.newIdea = newIdea;
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:detailViewController];
[self presentModalViewController:navigationController animated:YES];
[detailViewController release];
[navigationController release];
}
- (void)showMailView
{
mailComposerViewController.idea = selectedIdea;
[mailComposerViewController showPicker];
}
- (void)showSettingsView
{
SettingsViewController *settingsViewController = [[SettingsViewController alloc] initWithNibName:@"SettingsViewController" bundle:nil];
settingsViewController.delegate = self;
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:settingsViewController];
[self presentModalViewController:navigationController animated:YES];
[settingsViewController release];
[navigationController release];
}
#pragma mark -
#pragma mark SettingsViewControllerDelegate methods
- (void)reloadTheme
{
[self configureTheme];
}
#pragma mark - IdeaDetailDelegate
- (void)ideaDetailViewController:(IdeaDetailViewController *)ideaDetailViewController didSaveIdea:(Idea *)idea
{
[self.tableView reloadData];
[self updateTitle];
[self dismissModalViewControllerAnimated:YES];
}
- (void)ideaDetailViewControllerDidForceDelete:(IdeaDetailViewController *)ideaDetailViewController
{
[self.tableView reloadData];
[self updateTitle];
[self dismissModalViewControllerAnimated:YES];
[self.navigationController popViewControllerAnimated:NO];
}
#pragma mark -
#pragma mark UIActionSheetDelegate methods
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0) {
[self deleteCurrentObject];
}
}
#pragma mark -
#pragma mark Add a new object
- (void)insertNewObject {
[FlurryAPI logEvent:@"INSERT_IDEA"];
Idea *newIdea = [NSEntityDescription
insertNewObjectForEntityForName:@"Idea"
inManagedObjectContext:self.managedObjectContext];
[newIdea setValue:[NSDate date] forKey:@"timeStamp"];
if (selectedIdea) {
[newIdea setValue:selectedIdea forKey:@"parent"];
}
[self showDetailView:newIdea newIdea:YES];
}
- (void)deleteCurrentObject
{
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
[context deleteObject:selectedIdea];
NSError *error = nil;
if (![context save:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
[ApplicationHelper showApplicationError];
}
[self.navigationController popViewControllerAnimated:YES];
}
- (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 {
return [[self.fetchedResultsController fetchedObjects] count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"TableViewCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 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]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
[ApplicationHelper showApplicationError];
}
}
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
// The table view should not be re-orderable.
return NO;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
Idea *idea = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSString *cellText = [idea valueForKey:@"name"];
UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:17.0];
CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
return labelSize.height + 25;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
RootViewController *rootViewController = [[RootViewController alloc] initWithNibName:@"RootViewController" bundle:nil];
rootViewController.managedObjectContext = self.managedObjectContext;
Idea *idea = [self.fetchedResultsController objectAtIndexPath:indexPath];
rootViewController.selectedIdea = idea;
[self.navigationController pushViewController:rootViewController animated:YES];
[rootViewController release];
}
#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:@"Idea" 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:@"timeStamp" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
// Filter for parent_id
NSPredicate *predicate;
if (selectedIdea) {
predicate = [NSPredicate predicateWithFormat:@"parent == %@", selectedIdea];
} else {
predicate = [NSPredicate predicateWithFormat:@"parent == %@", [NSNull null]];
}
[fetchRequest setPredicate:predicate];
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
// For now I'm setting cacheName to nil as I don't think it will impact performances
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc]
initWithFetchRequest:fetchRequest
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
[aFetchedResultsController release];
[fetchRequest release];
[sortDescriptor release];
[sortDescriptors release];
NSError *error = nil;
if (![fetchedResultsController_ performFetch:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
[ApplicationHelper showApplicationError];
}
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 {
NSLog(@"Foo");
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];
[self updateTitle]; // reload title after deletion
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.
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
// In the simplest, most efficient, case, reload the table view.
[self.tableView reloadData];
}
*/
#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.
// For example: self.myOutlet = nil;
}
- (void)dealloc {
[fetchedResultsController_ release];
[managedObjectContext_ release];
[selectedIdea release];
[mailComposerViewController release];
[super dealloc];
}
@end