- Entering Weight Data
- Changing Weight Units
- Showing Weight History
- Showing Detail Views
- Wrapping Up
Showing Weight History
Now let’s shift over to our history view. Here, we display a list of all the entries in our WeightHistory. We will use a UITableView to present these entries, showing one entry per row. Let’s start by designing a custom cell for these rows.
Right-click the Views group and select New File > Objective-C Class. Make sure it is a subclass of UITableViewCell, and name it HistoryCell. Now open HistoryCell.h. Modify the header file as shown:
#import <UIKit/UIKit.h>#import "WeightEntry.h"
@interface HistoryCell : UITableViewCell@property (nonatomic, strong) IBOutlet UILabel* weightLabel;
@property (nonatomic, strong) IBOutlet UILabel* dateLabel;
- (void)configureWithWeightEntry:(WeightEntry*)entry
defaultUnits:(WeightUnit)unit;
@end
Unlike view controllers, outlets cannot be Control-dragged from the storyboard to a view’s header file. Instead, we need to manually declare them first. We’re also declaring a method to configure our cell—changing the contents of its labels based on the WeightEntry and WeightUnit arguments.
Switch to the implementation file. We’ll start by synthesizing our properties.
@synthesize weightLabel=_weightLabel; @synthesize dateLabel=_dateLabel;
Then implement configureWithWeightEntry:defaultUnits:.
- (void)configureWithWeightEntry:(WeightEntry*)entry defaultUnits:(WeightUnit)unit { self.weightLabel.text = [entry stringForWeightInUnit:unit]; self.dateLabel.text = [NSDateFormatter localizedStringFromDate:entry.date dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterShortStyle]; }
Here, we use our WeightEntry’s stringForWeighInUnit: method to set the weightLabel outlet with a correctly formatted weight string. Next, we use NSDateFormatter to create a properly localized date string using the short date and short time formats. We then assign this to our dateLabel outlet.
Now, let’s open the storyboard and zoom in on our history view. Select the prototype cell and switch to the Identity inspector. Set the cell’s class to HistoryCell. Then switch back to the Attributes inspector. Make sure the Accessory attribute is set to Disclosure Indicator. This will add a gray chevron on the right side of our cell.
Xcode provides two built-in accessories with very similar functions. Both the Disclosure Indicator and the Detail Disclosure indicate that the application has additional information related to this row. However, there are slight differences, both in the way they operate and in their intended use.
Detail Disclosure creates a round blue button with a white chevron. When the user taps the button, it should navigate to a detail view for the selected item. The Disclosure Indicator, on the other hand, just provides the gray chevron image. Here, the user must select the row itself, and they are then navigated to a sublist (usually containing additional options).
Arguably, Health Beat should use Detail Disclosure accessories—but I feel that having users select the row, not the disclosure button, works better. Besides, our detail view is a list (of sorts), so it’s not wholly inappropriate, and even Apple isn’t 100 percent consistent with their accessories.
Now, drag out two labels. Set the first label’s title to Weight. Make it 100 points wide, and set the font to 18-pt System Bold. Then drag it until it is vertically centered along the cell’s left margin. In the Size inspector, lock its Autosizing position to the top and the left side.
Make the second label right-aligned 12-pt System Italic with a light gray text color. Set its title to Short Date and Time. Then align it with the Weight label, stretched so it fills the area between the Weight label and the Disclosure Indicator accessory. Its Autosizing position should be locked to the top and the right side (Figure 4.21).
Figure 4.21 The finished history cell
Now, right-click the prototype cell and draw the connections from the dateLabel outlet to our Short Date and Time label. Draw a second connection from the weightLabel outlet to our Weight label. With that, our cell prototype is ready, and we just need to finish the HistoryViewController.
Let’s start by importing our HistoryCell class at the top of HistoryViewController.m.
#import "HistoryCell.h"
Now we need to clean up our temporary code. Our history list should only have a single section, so numberOfSectionsInTableView: should still return 1. However, we need a number of rows equal to the number of entries in our weight history. Modify tableView:numberOfRowsInSection: to return this value.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // We only have a single section. return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // Return the number of entries in our weight history. return [self.weightHistory.weights count]; }
Next, navigate to the tableView:cellForRowAtIndexPath: method, and modify this method as shown.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"History Cell"; HistoryCell *cell = [tableView dequeueReusableCellWithIdentifier: CellIdentifier]; // Configure the cell... WeightEntry* entry = [self.weightHistory.weights objectAtIndex:indexPath.row]; [cell configureWithWeightEntry:entry defaultUnits:self.weightHistory.defaultUnits]; return cell; }
It’s important to understand how table view cells work. We want to make our tables as efficient as possible, and there’s no point creating 10,000 separate cells if only ten of them can fit on the screen at a time. Therefore, when a cell scrolls off the screen, we should recycle it, reusing it the next time we need a new cell. Fortunately, UIKit can automatically do this for us.
To support cell reuse, we create a unique identifier for our cells. This is particularly important if you have different cells with different formats or even different classes. Each format needs its own identifier. When we need a new cell, we check to see if we have any available, unused cells by calling dequeueReusableCellWithIdentifier: and passing in our cell identifier.
Before iOS 5, if this method couldn’t find an unused cell, it simply returned nil. We then had to create a new instance ourselves. In the simplest cases, this was not too difficult; however, if our table had a number of different cell types, the code could rapidly grow complex. Fortunately, iOS 5 has automated much of this for us.
As long as we’re using a cell prototype from our storyboard, or a cell from a nib that we’ve registered using registerNib:forCellReuseIdentifier:, the dequeueReusableCellWithIdentifier: method will always returns a valid cell object. It will still reuse an existing cell, if possible; however, if nothing’s available, it will automatically create a new cell for us.
As you can see, this greatly simplifies our tableView:cellForRowAtIndexPath: method. When we modified this method, we deleted more code than we added.
Our code grabs a HistoryCell instance using our HistoryCellIdentifier constant. This, of course, matches the identifier set in our storyboard. Then we get the WeightEntry that corresponds with the current row, and we pass that weight entry and our default units value into the cell’s configureWithWeightEntry:defaultUnits: method. This, in turn, properly sets the text in the cell’s labels.
If you run the application now, you can enter new weight values; however, they may not appear in the history view. This is because our application doesn’t yet update the history view when our model changes. Let’s fix that.
Responding to Changes in the Model
Navigate back to the top of the file, and add the following extension before the @implementation block:
@interface HistoryViewController() - (void)reloadTableData; - (void)weightHistoryChanged:(NSDictionary*) change; @end
This defines two private methods. The first, reloadTableData, will reload the entire table. We will call this whenever the default weight unit changes, since we will need to rewrite all the weight strings in all the cells.
The second method, weightHistoryChanged:, will be called whenever a WeightEntry is added to or removed from our history. In this case, we want to modify only the affected cells (adding or removing individual cells as needed).
Now, navigate to the viewDidLoad method and modify it as shown here:
- (void)viewDidLoad { [super viewDidLoad]; // Uncomment the following line to preserve // selection between presentations. // self.clearsSelectionOnViewWillAppear = NO; // Uncomment the following line to display an Edit button // in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem;// Register to receive KVO messages when the weight history
// changes.
[self.weightHistory addObserver:self
forKeyPath:KVOWeightChangeKey
options:NSKeyValueObservingOptionNew
context:nil];
// Register to receive messages when the default units change.
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(reloadTableData)
name:WeightHistoryChangedDefaultUnitsNotification
object:self.weightHistory];
}
The addObserver:forKeyPath:options:context: method registers our HistoryViewController as an observer of our weight history. Our controller will receive a notification whenever the list of weight entries changes. Notice that the KVOWeightChangeKey actually points to the private weightHistory property (see “The WeightHistory Class” in Chapter 3). We could observe the public weights property, but unfortunately, because it’s a virtual property we only receive a general notification that the array has changed—we don’t get any additional information about the change. When we observe the weightHistory array directly, we get additional information about the type of change and a list of the actual indexes that changed.
In many ways, using the KVOWeightChangeKey really lets us break the WeightHistory class’s encapsulation. In my opinion, this is not necessarily ideal, but by using a public variable for the key, we are essentially blessing this backdoor access. We are promising that we won’t change the underlying implementation without also changing KVOWeightChangeKey to match.
Realistically, however, we should change the WeightHistory code to manually throw the correct KVO notifications for the weights property and just get rid of the backdoor access. However, I wanted to show how to automatically generate KVO notifications using the keyPathsForValuesAffecting<key> method. This has the fortunate side effect of also highlighting some of the limits of this approach.
The addObserver:selector:name:object: method registers our controller to receive WeightHistoryChangedDefaultUnitsNotification messages from our model (and only from our model). When a matching notification is found, the notification center will call our reloadTableData method directly.
Next, we need to remove our observers when the view unloads. Modify the viewDidUnload method as shown here:
- (void)viewDidUnload {[self.weightHistory removeObserver:self
forKeyPath:KVOWeightChangeKey];
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super viewDidUnload]; }
This shows another difference between KVO and notifications. For KVO, we must remove each observer/key pair separately. For notifications, we have a convenience method that removes all notifications for a given observer.
Now we must respond to the notifications. We need to implement the observeValueForKeyPath:ofObject:change:context: method and our two private methods, reloadTableData and weightHistoryChanged:.
#pragma mark - Notification Methods - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if ([keyPath isEqualToString:KVOWeightChangeKey]) { [self weightHistoryChanged:change]; } }
All KVO notifications call the observer’s observeValueForKeyPath:ofObject:change:context: method. Here, we simply check to ensure that the notification’s key path matches the KVOWeightChangeKey. If that is the case, we call the weightHistoryChanged: method, passing in the change dictionary. We could process the changes here, but I like to keep the ObserveValueForKeyPath:ofObject:change:context: method as clean and simple as possible, typically using it to dispatch out to other methods. After all, this method will grow increasingly complex if we start adding new KVO notifications.
- (void)weightHistoryChanged:(NSDictionary*) change { // First extract the kind of change. NSNumber* value = [change objectForKey:NSKeyValueChangeKindKey]; // Next, get the indexes that changed. NSIndexSet* indexes = [change objectForKey:NSKeyValueChangeIndexesKey]; NSMutableArray* indexPaths = [[NSMutableArray alloc] initWithCapacity:[indexes count]]; // Use a block to process each index. [indexes enumerateIndexesUsingBlock: ^(NSUInteger indexValue, BOOL* stop) { NSIndexPath* indexPath = [NSIndexPath indexPathForRow:indexValue inSection:0]; [indexPaths addObject:indexPath]; }]; // Now update the table. switch ([value intValue]) { case NSKeyValueChangeInsertion: // Insert the row. [self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic]; break; case NSKeyValueChangeRemoval: // Delete the row. [self.tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic]; break; case NSKeyValueChangeSetting: // Index values changed...just ignore. break; default: [NSException raise:NSInvalidArgumentException format:@"Change kind value %d not recognized", [value intValue]]; } }
The KVO change dictionary becomes particularly useful when we are monitoring collections. It contains information on both the type of change that occurred and the affected indexes. In our weightHistoryChanged method, we start by extracting the type of change. There are four possible types: inserts, removals, replacements, and the somewhat oddly named “setting” changes.
The first two should be obvious. You are adding or deleting one or more elements in the collection. Replacement merely means you are changing the value at a given index in the collection. Setting changes mean you are changing the value of the key path itself. Usually, this occurs when you change the property’s value. For a collection, that means replacing the current collection with an entirely new one.
Next, we extract the set of affected indexes. Notice that the change dictionary returns an NSIndexSet. However, we need an NSArray of NSIndexPaths. We therefore need to convert our indexes.
Here, we’re using a block to iterate over our index set. The enumerateIndexesUsingBlock: method takes each index in the index set and passes it to the provided block. The block should have two arguments: an NSUInteger representing the current index, and a pointer to a BOOL. The pointer is an output-only argument. Setting its value to YES will stop the enumerations, causing enumerateIndexesUsingBlock: to return.
Our block simply takes the index and converts it to an index path. When dealing with UITableViews, the index path contains both the row and the section of a particular entry. Our table has only one section, so we just hard-code the section index to 0. The block then adds the new NSIndexPath to our indexPaths array. Notice how our block can access and modify objects in the same lexical scope. For more information on blocks, see “Blocks” in Chapter 2.
Finally, we update the table. We are primarily concerned with insertions and removals. If either of these occurs, we modify the corresponding rows in the table. We should not get any replacement changes, but we could see an accidental setting change (for example, when the model’s history array is deallocated); however, we can safely ignore these. For anything else, we throw an exception.
As you can see, this method only modifies the table rows that actually changed. Additionally, we animate our changes using UITableViewRowAnimationAutomatic. This tells the system to automatically select an animation style that will look good, based on the type of table view and the cell’s location within the table. In general, you should use automatic animation unless you have an overriding reason to use something else. This helps maintain consistency across applications.
Unfortunately, the new rows are inserted while the table view is offscreen, so the animation will finish before we can navigate to the history view. However, you will get to see the removals once we add editing support.
Our last private method is simply a wrapper around the table view’s reloadData method.
- (void)reloadTableData { [self.tableView reloadData]; }
This raises the question, why don’t we have the table view observe the WeightHistoryChangedDefaultUnitsNotification and let the notification center call its reloadData method directly? While this would simplify our HistoryViewController class, it creates a subtle bug.
We still need to remove our table view from the observer list before it is deallocated. Unfortunately, our viewDidUnload method occurs after the view has already been released. Worse yet, if we accidentally try to access self.tableView in the viewDidUnload method, we will actually force the view to reload. Since viewDidUnload is only called during memory shortages, grabbing additional memory to rebuild our table view could cause our app to crash. At the very least, it would short-circuit our controller’s attempt to free up some unneeded memory.
Using the view controller as the observer lets us cleanly register and unregister ourselves for notifications, even if we do end up just dispatching the call back to the table.
OK, run the application again. Try adding a few dates. You should see them appear in the history list, with the most recent weight at the top. Try switching from pounds to kilograms and back. The history view should update automatically (Figure 4.22).
Figure 4.22 Automatically updating when the default units change
Editing the History View
Now that we can add new weights, we really need a way to remove them. The easiest option is to enable editing in the table view. To do this, we just need to add our controller’s edit button to the navigation bar. The code is already located in viewDidLoad. We just need to uncomment it. While we’re at it, let’s delete the rest of the comments.
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.rightBarButtonItem = self.editButtonItem;
// Register to receive KVO messages when the weight history
// changes.
[self.weightHistory addObserver:self
forKeyPath:KVOWeightChangeKey
options:NSKeyValueObservingOptionNew
context:nil];
// Register to receive messages when the default units change.
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(reloadTableData)
name:WeightHistoryChangedDefaultUnitsNotification
object:self.weightHistory];
}
Pressing the edit button puts the table view in editing mode. By default, this displays a Delete icon beside each row. You can modify this behavior using several UITableViewDelegate methods, but for our case, the default behavior is exactly what we want.
Go ahead and run the app now. Enter a few weights, and then put the history view in edit mode. If you press one of the Delete icons, it will bring up a red confirmation button. However, pressing the confirmation button doesn’t do anything (Figure 4.23).
Figure 4.23 Editing the table
We still need to respond to the edit commands by both removing the row from the table and removing the corresponding WeightEntry from our model. To do this, uncomment and modify the tableView:commitEditingStyle:forRowAtIndexPath: method.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { [self.weightHistory removeWeightAtIndex:indexPath.row]; } }
Here we just verify that we are deleting an object. Then we remove the selected object from our weightHistory. That’s it. We’ve already built in support for removing table rows when entries are deleted from our model. Our existing notifications will trigger that code automatically. Additionally, we never add new entries from within the table view, so we don’t need to check for inserts here.
And that’s it. Build and run the application. Try adding and deleting weights. If everything works correctly, remember to commit your changes.
There’s a lot more to editing table views, of course. If you really want, you can add the ability to reorder the weights (though I don’t know why we would want that feature for this project). You could also add new weights directly from the table view. You can even allow multiple selections using UITableView’s allowsMultipleSelections and allowsMultipleSelectionsDuringEditing properties. However, I’ll leave those as homework.