To persist other information, a UIViewController is given a chance to encode any relevant data in a process very similar to archiving. In fact, both encoding processes use an NSCoder object to do the work. You will use this to save out any necessary information in the view controller subclasses.
In BNRDetailViewController.m, encode the itemKey for the currently displayed BNRItem.
- (void)encodeRestorableStateWithCoder:(NSCoder *)coder { [coder encodeObject:self.item.itemKey forKey:@"item.itemKey"]; [super encodeRestorableStateWithCoder:coder]; }
Then implement the decoding method to search through the BNRItemStore for the appropriate BNRItem.
- (void)decodeRestorableStateWithCoder:(NSCoder *)coder { NSString *itemKey = [coder decodeObjectForKey:@"item.itemKey"]; for (BNRItem *item in [[BNRItemStore sharedStore] allItems]) { if ([itemKey isEqualToString:item.itemKey]) { self.item = item; break; } } [super decodeRestorableStateWithCoder:coder]; }
Build and run the application and drill down into a BNRItem. Then perform the state restoration steps again. This time, the values on the BNRDetailViewController will correctly reflect the BNRItem being displayed.
There is still one problem: the text fields and labels are being populated with the values of the BNRItem. If the user has typed in some other value, those values will be lost upon state restoration.
You will fix this by saving the current text field values into the BNRItem. Since view controller encoding occurs after the application has entered the background, you will also need to save the store again.
In BNRDetailViewController.m update the encode method.
- (void)encodeRestorableStateWithCoder:(NSCoder *)coder { [coder encodeObject:self.item.itemKey forKey:@"item.itemKey"]; // Save changes into item self.item.itemName = self.nameField.text; self.item.serialNumber = self.serialNumberField.text; self.item.valueInDollars = [self.valueField.text intValue]; // Have store save changes to disk [[BNRItemStore sharedStore] saveChanges]; [super encodeRestorableStateWithCoder:coder]; }
The BNRDetailViewController is now saving and restoring its state beautifully. Without a lot of work on your part, your users get a better experience. Now let’s turn our attention to the BNRItemsViewController.