Upload
lamthuy
View
215
Download
1
Embed Size (px)
Citation preview
MVC & OnwardsCS 442: Mobile App Development Michael Saelee
Computer ScienceScience
Agenda- Recap: view-controller communication
- Delegation as a general pattern
- “Observer” pattern
- Controller responsibilities & MVC
- Multiple scenes & controllers
Computer ScienceScience
“Simple” view-controller communication:
- target-action (view push)
- designate method as @IBAction
- outlet (controller push/pull)
- designate attribute as @IBOutlet
Computer ScienceScience
For complex views, view defines API for controller to adopt: delegation protocol
- enables view push & pull
- enables/simplifies reuse of complex UI widgets
Computer ScienceScience
- but delegation isn’t just used for view-controller communication
- same mechanism used for relaying app lifecycle notifications to our custom code
- App → UIApplicationDelegate
- Recall high-level app event callbacks
Computer ScienceScience
from Apple’s iOS App Programming Guide
Computer ScienceScience
from Apple’s iOS App Programming Guide
Computer ScienceScience
AppDelegate also receives events that are not handled by views or view controllers
• low-level touch and motion events
• functions as “catch-all” handler
Computer ScienceScience
AppDelegateUIApplication
superview
Window
superview
View
ViewControllerView
superview
View
designated event recipient
iOS responder chain
Computer ScienceScience
- two basic ways for an object to be the designated recipient of an event 1. hit-testing for touches
2. assumes first responder status
- note: designated recipient doesn’t have to be a view (any subclass of UIResponder)
View
designated event recipient
Computer ScienceScience
Classes in the view system(from “View Controller Programming Guide for iOS”
Computer ScienceScience
sometimes it’s handy to broadcast/receive notifications in non-default ways
• notifications outside our “scope”
• notifications that aren’t sent by default
• app-specific notifications
Computer ScienceScience
Observer Pattern- any object can register to receive
notifications of specific events
- One mechanism: notification centers - Enables action at a distance (not
necessarily a good thing!)
Computer ScienceScience
Delegation embodies the separation of (1) the thing where events happen and (2) the thing that processes events
(1) is the view
(2) is the view controller
Computer ScienceScience
But the list of responsibilities is lopsided.
(1) just has to map inputs to high-level actions; e.g., a touch in a table area to cell selection
(2) has to (a) map an action to a semantic intent, then (b) actually carry out that intent
Computer ScienceScience
(a) is the controller’s job, but
(b) often requires domain-specific knowledge
Computer ScienceScience
to allow for reuse (and modular design) of (b) — would like to extricate this from the controller’s implementation
Computer ScienceScience
objects to receive notifications of state changes. However, there is a theoretical problem with this design.View objects and model objects should be the most reusable objects in an application. View objects representthe "look and feel" of an operating system and the applications that system supports; consistency in appearanceand behavior is essential, and that requires highly reusable objects. Model objects by definition encapsulatethe data associated with a problem domain and perform operations on that data. Design-wise, it's best tokeep model and view objects separate from each other, because that enhances their reusability.
In most Cocoa applications, notifications of state changes in model objects are communicated to view objectsthrough controller objects. Figure 4-6 shows this different configuration, which appears much cleaner despitethe involvement of two more basic design patterns.
Figure 4-6 Cocoa version of MVC as compound design pattern
MediatorStrategy
Controller
ModelViewCommandComposite
Observer
The controller object in this compound design pattern incorporates the Mediator pattern as well as theStrategy pattern; it mediates the flow of data between model and view objects in both directions. Changesin model state are communicated to view objects through the controller objects of an application. In addition,view objects incorporate the Command pattern through their implementation of the target-action mechanism.
Note: The target-action mechanism, which enables view objects to communicate user input and choices,can be implemented in both coordinating and mediating controller objects. However, the design of themechanism differs in each controller type. For coordinating controllers, you connect the view object to itstarget (the controller object) in Interface Builder and specify an action selector that must conform to a certainsignature. Coordinating controllers, by virtue of being delegates of windows and the global applicationobject, can also be in the responder chain. The bindings mechanism used by mediating controllers alsoconnects view objects to targets and allows action signatures with a variable number of arguments of arbitrarytypes. Mediating controllers, however, aren't in the responder chain.
There are practical reasons as well as theoretical ones for the revised compound design pattern depicted inFigure 4-6, especially when it comes to the Mediator design pattern. Mediating controllers derive fromconcrete subclasses of NSController, and these classes, besides implementing the Mediator pattern, offermany features that applications should take advantage of, such as the management of selections andplaceholder values. And if you opt not to use the bindings technology, your view object could use a mechanismsuch as the Cocoa notification center to receive notifications from a model object. But this would requireyou to create a custom view subclass to add the knowledge of the notifications posted by the model object.
In a well-designed Cocoa MVC application, coordinating controller objects often "own" mediating controllers,which are archived in nib files. Figure 4-7 shows the relation of the two types of controller objects.
The Model-View-Controller Design Pattern 1632009-10-19 | © 2009 Apple Inc. All Rights Reserved.
CHAPTER 4
Cocoa Design Patterns
Computer ScienceScience
MVC is central to the architecture of virtually all native iOS apps, and is found at all levels of the development stack
Computer ScienceScience
Turns out the one-controller-per-scene tale is not really accurate …
• often need a controller to manage transitions between separate, per-screen controllers
• overarching “container” controllers
Computer ScienceScience
Computer ScienceScience
Built-in controllers for this!
Computer ScienceScience
View controller classes in UIKit(from “View Controller Programming Guide for iOS”
Computer ScienceScience
Navigation container controller(from “View Controller Programming Guide for iOS”
Computer ScienceScience
Tab bar container controller(from “View Controller Programming Guide for iOS”
Computer ScienceScience
Good news: intended for use without subclassing • typically drop into Storyboard &
customize in code if necessary
• segues are used as to connect controllers — e.g., to pass data
• (true even without container controllers)
Computer ScienceScience
Computer ScienceScience
A segue tracks:
1. Source controller
2. Destination controller
3. Segue “name” (unique in storyboard)
Computer ScienceScience
When a segue is triggered:
- the destination controller is created
- prepareForSegue is called in source
- an [animated] transition from source to destination controller takes place
Computer ScienceScience
Segues seem magical, but really just add another layer of abstraction on top of what we already have
Computer ScienceScience
Controller transition without segue:
1. Event (e.g., button tap) triggers action
2. Action method creates dest controller
3. [Pass data to dest in action method]
4. Use presentViewController to activate dest controller
Computer ScienceScience
Controller transition with segue:
1. Event triggers creation of segue object
2. Segue populates its src/dest controllers
3. prepareForSegue called in src controller
4. [Pass data to dest in prepareForSegue]
Computer ScienceScience
Controller transition with segue:
5. Segue object’s perform is invoked
6. [perform method animates transition]
7. perform calls presentViewController to complete transition
Computer ScienceScience
If we use built-in segues, most of this is automatic (i.e., invisible)
Computer ScienceScience
Can do away (sometimes) with cumbersome & wordy delegate mechanism
Computer ScienceScience
When a segue is triggered:
- the destination controller is created
- prepareForSegue is called in source
- good place to send data to destination
(slight problem)
Computer ScienceScience
(sometimes we want to return to an existing controller/scene)
Computer ScienceScience
“Unwind” segues let us return to an unwind action in a previous controller
Computer ScienceScience
Conveniently, segue stores and retains source controller — can retrieve data in destination before source goes away
/* Sample unwind segue action */ - (IBAction)unwindSegue:(UIStoryboardSegue *)segue { ViewController *srcController = segue.sourceViewController;
/* retrieve data from srcController */
/* note: manually dismissing srcController isn’t done here! */ }
Computer ScienceScience
§Container controllers
Computer ScienceScience
so far, we can create a modal VC relationship
… but that’s not always enough to build/describe a complex app
Computer ScienceScience
Computer ScienceScience
Computer ScienceScience
other typical VC relationships:
- hierarchical / drill-down
- sibling / parallel
— “navigation”— “tabbed”
Computer ScienceScience
in both cases, there is some overarching context for the related VCs
navigation bar
tab bar
Computer ScienceScience
UINavigationController & UITabBarController = container view controllers
Computer ScienceScience
container view controllers track and manage transitions between other view controllers
- implement custom transitions
- simplify controller management & communication
Computer ScienceScience
e.g., UINavigationController
Computer ScienceScience
views managed by different VCs on screen simultaneously (previously a no-no)
Computer ScienceScience
NavController manages a stack of related view controllers
Computer ScienceScience
NavController also exposes an API for managing the navigation & tool bars
Computer ScienceScience
Computer ScienceScience
Computer ScienceScience
UINavigationControllerCreating Navigation Controllers
– initWithRootViewController: Accessing Items on the Navigation Stack
topViewController property visibleViewController property viewControllers property – setViewControllers:animated:
Pushing and Popping Stack Items – pushViewController:animated: – popViewControllerAnimated: – popToRootViewControllerAnimated: – popToViewController:animated:
UIViewController Getting the Navigation controller
navigationController property Configuring a Navigation Interface
navigationItem property hidesBottomBarWhenPushed property – setToolbarItems:animated toolbarItems property
UINavigationItem Getting and Setting Properties
title property backBarButtonItem property hidesBackButton property
Customizing Views leftBarButtonItem property rightBarButtonItem property