Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Beginning iOS5 Development.pdf
Скачиваний:
7
Добавлен:
09.05.2015
Размер:
15.6 Mб
Скачать

376

CHAPTER 10: Storyboards

Why are we using KVC here instead of just setting the delegate directly? One of the benefits of KVC is that it frees us from knowing the specifics of other classes’ interfaces, which leads to less tightly coupled code. If we wanted to call the method directly, we would need to declare an interface of some kind that included the setDelegate: method, and cast our destination variable to be a type that implemented that method. Using KVC, our code doesn’t need to know anything about the setDelegate: method (apart from the fact that the receiver responds to it), so we don’t need to have any declared interface to it.

BIDTaskListController doesn’t import BIDTaskDetailController’s header, and, in fact, doesn’t even know that it exists, and that’s a good thing! In general, the fewer dependencies you have between classes, the better. Properly applied, KVC can help you move your code in that direction.

Then we put the selected task and the index of the selected row into a dictionary to pass along to the detail view controller. We need to include the row index here so that later on, when the detail view is done, its controller can pass us back the same index so we know which task to change. Otherwise, we would just get back a string and have no idea where it belongs in our list.

if ([destination respondsToSelector:@selector(setSelection:)]) { // prepare selection info

NSIndexPath *indexPath = [self.tableView indexPathForCell:sender]; id object = [self.tasks objectAtIndex:indexPath.row];

NSDictionary *selection = [NSDictionary dictionaryWithObjectsAndKeys: indexPath, @"indexPath",

object, @"object", nil];

[destination setValue:selection forKey:@"selection"];

}

Just as when we set the destination’s delegate, we set its selection using KVC. Right now, our detail view controller doesn’t have a selection property either, but we’re about to change that.

Handling Task Details

Select BIDTaskDetailViewController.h. You’ll see the textView property that was added earlier when you dragged an outlet from the storyboard. Now, add two more properties, as shown here:

#import <UIKit/UIKit.h>

@interface BIDTaskDetailController : UIViewController @property (weak, nonatomic) IBOutlet UITextView *textView;

@property (copy, nonatomic) NSDictionary *selection; @property (weak, nonatomic) id delegate;

@end

Note that the selection property specifies copy storage (which is normally what we use whenever we’re dealing with value-based classes such as NSString and NSDictionary), but delegate specifies weak storage. We need to use weak storage for the delegate property so that we don’t accidentally retain our delegate, who may already be retaining us! In our case, we happen to know that the delegate isn’t retaining this object, but the

www.it-ebooks.info

CHAPTER 10: Storyboards

377

standard pattern used throughout Cocoa Touch is to make sure that delegates aren’t retained, and there’s no reason for us to do anything different here.

Switch to BIDTaskDetailViewController.m, and add some code near the top to synthesize getters and setters for our new properties:

@implementation BIDTaskDetailController @synthesize textView;

@synthesize selection; @synthesize delegate;

.

.

.

Scroll down a bit, and you’ll see that the viewDidLoad method is commented out by default. Remove the comment markers, and insert the code shown here:

- (void)viewDidLoad

{

[super viewDidLoad];

textView.text = [selection objectForKey:@"object"]; [textView becomeFirstResponder];

}

By the time this code is called, the segue is already underway, and the list view controller has set up our selection property. We pull out the value it contains, and pass it along to the text view. Then we tell the text view to become the First Responder, effectively saying, “tag, you’re it,” which will make the on-screen keyboard appear immediately.

Run your app, navigate your way into the task list, and select a task. You should see its value appear in an editable text field. So far, so good.

Passing Back Details

Now all that’s left is to bring the user’s edits back into the list. Unfortunately, our detail view won’t be sent the prepareForSegue:sender: method when the user hits the back button. That method is called only when a segue is pushing a new controller onto the stack, not when it’s popping one off. Instead, we’ll use a standard UIViewController method to implement something similar to what we did in BIDTaskListController. Add this method just after viewDidLoad:

- (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated];

if ([delegate respondsToSelector:@selector(setEditedSelection:)]) {

//finish editing [textView endEditing:YES];

//prepare selection info

NSIndexPath *indexPath = [selection objectForKey:@"indexPath"]; id object = textView.text;

NSDictionary *editedSelection = [NSDictionary dictionaryWithObjectsAndKeys: indexPath, @"indexPath",

www.it-ebooks.info

378

CHAPTER 10: Storyboards

object, @"object", nil];

[delegate setValue:editedSelection forKey:@"editedSelection"];

}

}

Here, we’re setting our delegate’s editedSelection property, if it has one, again using KVC. As before, this frees us from needing to know anything in particular about the other controller class. The only piece of this that might seem new to you is the call to [textView endEditing:YES], which simply forces the text view to finish any editing the user may have been doing so that its text value (which we grab a few lines later) is up to date.

Making the List Receive the Details

The final piece in this puzzle is ready to be put in place. We need to go back to the list view controller to make sure it can receive the editedSelection and do something reasonable with it. Return to BIDTaskListController.m, and make the following changes to the class extension at the top:

@interface BIDTaskListController ()

@property (strong, nonatomic) NSArray *tasks;

@property (strong, nonatomic) NSMutableArray *tasks; @property (copy, nonatomic) NSDictionary *editedSelection;

@end

.

.

.

The first change is there to turn the tasks property into a mutable array, so that we can change it when the user edits a task. The editedSelection property will contain the edited value passed back from the detail controller, as we just described.

Next, synthesize a getter and setter for editedSelection:

.

.

.

@implementation BIDTaskListController

@synthesize tasks;

@synthesize editedSelection;

Then make a slight change to viewDidLoad, replacing our old NSArray usage with

NSMutableArray:

- (void)viewDidLoad

{

[super viewDidLoad];

.

.

.

self.tasks = [NSArray arrayWithObjects:

www.it-ebooks.info

CHAPTER 10: Storyboards

379

self.tasks = [NSMutableArray arrayWithObjects:

.

.

.

Finally, we’re going to implement a custom setter for the editedSelection property. This will replace the setter that was implicitly created by the earlier @synthesize declaration. You can place this method at the end of the file, just before @end:

- (void)setEditedSelection:(NSDictionary *)dict { if (![dict isEqual:editedSelection]) {

editedSelection = dict;

NSIndexPath *indexPath = [dict objectForKey:@"indexPath"]; id newValue = [dict objectForKey:@"object"];

[tasks replaceObjectAtIndex:indexPath.row withObject:newValue]; [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]

withRowAnimation:UITableViewRowAnimationAutomatic];

}

}

This method pulls out the index and value (representing the edited item) that were passed back to us. It then puts the new value into the correct place in our tasks array, and reloads the corresponding cell so that the correct value is displayed.

Run your app again, navigate to the task list, pick a task, and edit it. When you then tap the back button, you’ll see that the edited value replaces the old value in the list. Moreover, since the affected cell is actually reloaded, the cell’s type can change from plainCell to attentionCell and vice versa, depending on the edited value. Try adding the word URGENT to a task that doesn’t already have it, or removing the word from one that does to see what happens.

If Only We Could End with a Smooth Transition

Now that you’ve been flipping through storyboards, have you flipped for them? We think they’re great for all kinds of navigation-based applications, and we’re going to use them a few more times in this book. As we mentioned at the beginning of the chapter, a downside to using storyboards at the time of this writing is that they work only with iOS 5 and later, which means that you’re limited to people who have upgraded or have just purchased a new device. Over time, this situation will change as more and more people upgrade to iOS 5.

Moving on, it’s time to consider even more navigation issues as you learn about iPadspecific view controllers in Chapter 11.

www.it-ebooks.info

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]