SlideShare uma empresa Scribd logo
1 de 48
Baixar para ler offline
AppDelegate
                             vs.
                     NSNotificationCenter
                         What they are, and some Pros and Cons


                                                              Kenji Hollis
                                                           March 03, 2009
                                                   WillowTree Consulting Group
Tuesday, March 3, 2009
What is a Delegate?
                    • An object that acts on events
                    • Generally named “ClassXYZDelegate”
                    • Allows objects to manipulate one-another
                         without the need for inheritance
                    • Used by most Cocoa Touch classes
                    • Should be implemented using formal
                         protocols
                    • Think of them as “callbacks”, most of which
                         are optional.
Tuesday, March 3, 2009
Target-Action
                    • Target: the delegate class that implements a
                         method to call when an event is performed.
                    • Action: the method that responds to the
                         target event.
                    • Used by UIKit. Example, UIAlertView: set
                         the delegate (target), implement dismissal
                         delegate and respond to the request
                         (action).


Tuesday, March 3, 2009
Quick “How-To”
                            In your accessor class header:
                Class .h file:
                @interface Class {
                    id parentDelegate;
                }

                - (id)delegate;
                - (void)setDelegate:(id)newDelegate;




Tuesday, March 3, 2009
Quick “How-To”
                         Implement the code in the accessor class:
                Class .m file:
                - (id)delegate {
                    return parentDelegate;
                }

                - (void)setDelegate:(id)newDelegate {
                    parentDelegate = newDelegate;
                }




Tuesday, March 3, 2009
Quick “How-To”
                   Calling a delegate function from the accessor:
                Class .m file:
                - (void)performEvent {
                    if ([parentDelegate respondsToSelector:@selector(myEvent)]) {
                        [parentDelegate myEvent];
                    }
                }


                We use “respondsToSelector” to verify that the
                 selector exists in the implementing delegate
                 class. Note the “blind call” to the “myEvent”
                                    function.

Tuesday, March 3, 2009
Quick “How-To”
                                     Alternate method:
                Class .m file:
                - (void)performEvent {
                    if ([parentDelegate respondsToSelector:@selector(myEvent)]) {
                        [parentDelegate performSelector:@selector(myEvent)];
                    }
                }


                       We are calling the selector by using
                  “performSelector” instead of blindly calling the
                     member. Here, “myEvent” is the action,
                         “parentDelegate” is the target.

Tuesday, March 3, 2009
Delegate Use:
                    • A delegate is called after tapping a line in a
                         UITableView, or tapping a button in a
                         UIAlertView.
                    • Telling the application to switch to a
                         different tab view.
                    • Responding to an application interruption.
                    • Running an operation that may block the
                         application until complete (with a “Please
                         wait” box)
Tuesday, March 3, 2009
An example delegation
                                        Modal Confirmation Dialog button clicked,
                                        generates “OK” or “Cancel” action event.


                             “OK” Clicked event                       “Cancel” Clicked event


                  Display progress pane “Please wait ...”         Store “Cancel” result in the DB


                         HTTP Post sent synchronously                   Close modal dialog
                           to record confirmation


                               Wait for response
                             from the HTTP Post


                   Parse response, store result in DB,
                 close modal dialog and progress pane.
Tuesday, March 3, 2009
What is an
                               AppDelegate?
                    • Serves as the root controller of your
                         application.
                    • Contains methods to handle application
                         start, shutdown, and interruption.
                    • Contains the setup code for your
                         application’s main window.
                    • Generally knows how to control your
                         application from the top level (ie. change
                         tab bar views, save prefs, etc.)
Tuesday, March 3, 2009
AppDelegate Example
                 Delegate functions in an example AppDelegate:
                - (void)applicationDidFinishLaunching:(UIApplication *)app {
                    // ... Set up your code here ...
                }

                - (void)function_1 {
                    // ... Do something in the app view controller ...
                }

                - (void)function_2 {
                    // ... Manipulate the tab controller here ...
                }

                - (void)function_3 {
                    // ... Miscellaneous call here ...
                }

                - (void)function_4;
                - (void)function_5;

                // ... and on ... and on ... and on...
Tuesday, March 3, 2009
Calling the
                 AppDelegate members:
                    • First, get access to the AppDelegate by
                         grabbing the
                         [[UIApplication sharedApplication] delegate]

                         object.
                    • Cast that to the application object.
                    • Call the delegate methods where
                         appropriate.

Tuesday, March 3, 2009
Call the AppDelegate
                               members:
                - (void)alertView:(UIAlertView *)alertView
                        didDismissWithButtonIndex:(NSInteger)button {

                         // Retrieve the application delegate
                         MyApplication *myApp = (MyApplication *)
                                                [[UIApplication sharedApplication]
                                                 delegate];

                         // Call the application delegate method.
                         [myApp function_1];

                }




Tuesday, March 3, 2009
Delegate Pros
                    • Function declarations must be strictly
                         defined, or they will not be performed
                    • Delegate functions are almost always
                         guaranteed to fire when the selector is
                         called
                    • Delegates can be reused as often as the
                         programmer sees fit, from several classes
                    • Often used in conjunction with modal
                         operations, so they’re easier to debug
                    • Can be called asynchronously.
Tuesday, March 3, 2009
Delegate Cons
                    • If a delegate method is not defined
                         properly, it will not be performed, or it may
                         crash the app if called blindly.
                    • If a delegate method signature changes, it
                         has to be changed in all classes that call it.
                    • Because most functions are called
                         synchronously, they can tie up the app if
                         expensive operations are performed.


Tuesday, March 3, 2009
AppDelegate Pros:
                    • Provide direct access to the application’s
                         view controllers and layout control.
                    • Provide simple, direct access to the root
                         application.
                    • Controls how the application responds to
                         interruptions, startup, and shutdown. This
                         is provided to you by the
                         UIApplicationDelegate protocol.


Tuesday, March 3, 2009
AppDelegate Overuse:
                    • AppDelegates tend to get filled up with too
                         many member functions, so the
                         AppDelegate turns into a giant mess.
                    • People often use the AppDelegate to get
                         access to their view controller functions.
                    • Miscellaneous functions are often placed in
                         the AppDelegate when they could be
                         otherwise placed in a utility class.


Tuesday, March 3, 2009
How I’ve used
                               Delegates
                    • Controlled application flow by switching
                         tab views at the application top-level.
                    • Swapped views when the application
                         changes from portrait to landscape mode.
                    • Initialized the application by copying a read-
                         only database into a read/write directory.
                    • Preloaded data from a remote web call on
                         application first load.
                    • The list goes on.
Tuesday, March 3, 2009
What is a Notification?
                    • A queued message with a payload
                    • Sent application-wide, not to a specific class
                    • Posted “Immediately”, asynchronously, or
                         when convenient to the OS
                    • A single queued message can be received
                         and processed by multiple observers
                    • Can be sent with no registered observers,
                         and your application won’t crash!
Tuesday, March 3, 2009
Setting up the observer
                            This class receives an event message:
                Class .m file registering the observer:
                - (id)init ... {
                    [[NSNotificationCenter defaultCenter]
                      addObserver:self
                      selector:@selector(selector1:)
                      name:@”MY_SELECTOR_1”
                      object:nil];
                }

                - (void)selector1:(NSNotification *)notification {
                    NSObject *obj = [notification object];

                         if ([obj isKindOfClass:[NSDictionary class]]) {
                             // ... Do dictionary payload functionality here.
                         } else {
                             // ... Perform non-object payload functionality here.
                         }
                }
Tuesday, March 3, 2009
Sending the notification
                     This function sends the notification message:
                Class .m file sending the notification:
                - (void)myNotifier {
                    [[NSNotificationCenter defaultCenter]
                        postNotificationName:@”MY_SELECTOR_1”];

                         NSDictionary *myDictionary = [NSDictionary
                             dictionaryWithContentsOfFile:@”myFile.plist”];

                         [[NSNotificationCenter defaultCenter]
                             postNotificationName:@”MY_SELECTOR_1”
                             object:myDictionary];
                }




Tuesday, March 3, 2009
Don’t forget to
                                 deregister!
                Class .m file registering the observer:
                - (void)dealloc {
                    [super dealloc];

                         [[NSNotificationCenter defaultCenter]
                           removeObserver:self
                           name:@”MY_SELECTOR_1”
                           object:nil];
                }


                  Note: If you don’t de-register the observer, the
                     class will receive multiple copies of the
                                    notification.

Tuesday, March 3, 2009
Example Notifications
                    • Sending an application-wide status change
                         or refresh message
                    • Notifying the application when a network
                         change occurs
                    • When network data or a packet is received
                         and needs to be processed asynchronously
                    • Sending a message to more than one
                         listener at a time

Tuesday, March 3, 2009
Notification Flow




Tuesday, March 3, 2009
Notification Flow
                    Notification
                     + Payload




Tuesday, March 3, 2009
Notification Flow
                    Notification
                     + Payload




Tuesday, March 3, 2009
Notification Flow
                    Notification
                                  NSNotificationCenter
                     + Payload




Tuesday, March 3, 2009
Notification Flow
                    Notification
                                  NSNotificationCenter
                     + Payload




Tuesday, March 3, 2009
Notification Flow
                    Notification
                                             NSNotificationCenter
                     + Payload




                                  Observer




Tuesday, March 3, 2009
Notification Flow
                    Notification
                                             NSNotificationCenter
                     + Payload




                                  Observer




Tuesday, March 3, 2009
Notification Flow
                    Notification
                                             NSNotificationCenter
                     + Payload




                                  Observer




                             Operation(s)


Tuesday, March 3, 2009
Notification Flow
                    Notification
                                             NSNotificationCenter
                     + Payload




                                  Observer




                             Operation(s)


Tuesday, March 3, 2009
Notification Flow
                    Notification
                                             NSNotificationCenter
                     + Payload




                                  Observer        Observer




                             Operation(s)


Tuesday, March 3, 2009
Notification Flow
                    Notification
                                             NSNotificationCenter
                     + Payload




                                  Observer        Observer




                             Operation(s)


Tuesday, March 3, 2009
Notification Flow
                    Notification
                                             NSNotificationCenter
                     + Payload




                                  Observer        Observer         Observer




                             Operation(s)


Tuesday, March 3, 2009
Notification Flow
                    Notification
                                             NSNotificationCenter
                     + Payload




                                  Observer        Observer         Observer




                             Operation(s)


Tuesday, March 3, 2009
Notification Flow
                    Notification
                                             NSNotificationCenter
                     + Payload




                                  Observer        Observer          Observer




                             Operation(s)                          Operation(s)


Tuesday, March 3, 2009
Notification Flow
                    Notification
                                             NSNotificationCenter
                     + Payload




                                  Observer        Observer          Observer




                             Operation(s)                          Operation(s)


Tuesday, March 3, 2009
Notification Flow
                    Notification
                                             NSNotificationCenter
                     + Payload




                                  Observer        Observer          Observer




                             Operation(s)       Operation(s)       Operation(s)


Tuesday, March 3, 2009
A real-world example
                                               CoreLocationUpdate


                                               NSNotificationCenter


                             Observer 1            Observer 2            Observer 3


                         Hit geonames.org to    Store GPS data in    Calculate speed and
                         cross-reference GPS      SQL database             bearing


                          Update label on                             Update label on
                          screen with data                            screen with data



                 All of these operations happen asynchronously.
Tuesday, March 3, 2009
Notification Pros
                    • “Fire and Forget”
                    • A single notification can be processed by
                         multiple listeners
                    • Notifications can be posted to the queue
                         with different “posting styles” or priorities
                    • Notifications can be coalesced so they can
                         be sent in pairs or alphabetically
                    • Almost always used asynchronously.
Tuesday, March 3, 2009
Notification Cons
                    • If you don’t de-register a handler, you could
                         process a notification message multiple
                         times. (Typically, de-registration is done in
                         the dealloc member function.)
                    • Sending asynchronous notifications can be
                         hard to debug, like threads.
                    • The order in which notifications are
                         received by registered listeners is not
                         guaranteed.
Tuesday, March 3, 2009
How I’ve used
                              Notifications
                    • Wrote an application-wide CoreLocation
                         wrapper that notifies when location range
                         changes (remember the real-world
                         example?)
                    • Sent notifications to update multiple views
                         when a database change occurred.
                    • Sent notifications when XML lines of data
                         are parsed one-at-a-time.


Tuesday, March 3, 2009
Delegate + Notification
                        Scenario:
                    • SQL Insert/Update service listens for
                         notifications, with a payload containing
                         insert or update SQL data.
                    • When the SQLUpdate call completes, it
                         fires off a new notification indicating new
                         data has been populated.
                    • A Notification is received, and the affected
                         UITableView then calls “refreshData” and
                         updates itself with the new SQL data, using
                         delegates to populate and refresh itself.
Tuesday, March 3, 2009
Notification Extras:
                    • You can enqueue notifications using
                         “enqueueNotification” for finer notification
                         control.
                    • You can create your own
                         NSNotificationCenter queue for even finer
                         control.
                    • You can pair notifications up alphabetically
                         or by object for “in order” event firing.


Tuesday, March 3, 2009
Things to think about...
                    • Cocoa touch uses a large combination of
                         delegates and notification calls.
                    • You can see lots of fun things the UI
                         does by using Categories on the
                         NSNotificationCenter class.
                    • If you end up using NSNotificationCenter
                         in your app, try experimenting with the
                         “enqueueNotification” function for finer
                         grained control.
Tuesday, March 3, 2009
A Quick Demo!!!

                    • Simple demo that shows
                         NSNotificationCenter being overridden
                         with Categories, so we can see those “fun
                         things”




Tuesday, March 3, 2009
Thank you!
                    • khollis@willowtreeconsulting.com
                    • http://www.bitgatemobile.com/
                    • Twitter: @KenjiHollis
                    • kenji.hollis on Skype
                    • 303-521-1864

                    • Questions or comments?   Speak up!!
Tuesday, March 3, 2009

Mais conteúdo relacionado

Mais procurados

Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1PRN USM
 
Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892renuka gavli
 
Dependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHPDependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHPmtoppa
 
Large-Scale JavaScript Development
Large-Scale JavaScript DevelopmentLarge-Scale JavaScript Development
Large-Scale JavaScript DevelopmentAddy Osmani
 
Advance Java Programming (CM5I) 2.Swing
Advance Java Programming (CM5I) 2.SwingAdvance Java Programming (CM5I) 2.Swing
Advance Java Programming (CM5I) 2.SwingPayal Dungarwal
 
Session2-J2ME development-environment
Session2-J2ME development-environmentSession2-J2ME development-environment
Session2-J2ME development-environmentmuthusvm
 
The AWT and Swing
The AWT and SwingThe AWT and Swing
The AWT and Swingadil raja
 
Z blue introduction to gui (39023299)
Z blue   introduction to gui (39023299)Z blue   introduction to gui (39023299)
Z blue introduction to gui (39023299)Narayana Swamy
 
Session 3 J2ME Mobile Information Device Profile(MIDP) API
Session 3 J2ME Mobile Information Device Profile(MIDP)  APISession 3 J2ME Mobile Information Device Profile(MIDP)  API
Session 3 J2ME Mobile Information Device Profile(MIDP) APImuthusvm
 
Advance Java Programming (CM5I) 1.AWT
Advance Java Programming (CM5I) 1.AWTAdvance Java Programming (CM5I) 1.AWT
Advance Java Programming (CM5I) 1.AWTPayal Dungarwal
 
Swing and Graphical User Interface in Java
Swing and Graphical User Interface in JavaSwing and Graphical User Interface in Java
Swing and Graphical User Interface in Javababak danyal
 

Mais procurados (15)

Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1
 
Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892
 
GUI programming
GUI programmingGUI programming
GUI programming
 
Dependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHPDependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHP
 
Large-Scale JavaScript Development
Large-Scale JavaScript DevelopmentLarge-Scale JavaScript Development
Large-Scale JavaScript Development
 
Advance Java Programming (CM5I) 2.Swing
Advance Java Programming (CM5I) 2.SwingAdvance Java Programming (CM5I) 2.Swing
Advance Java Programming (CM5I) 2.Swing
 
Session2-J2ME development-environment
Session2-J2ME development-environmentSession2-J2ME development-environment
Session2-J2ME development-environment
 
The AWT and Swing
The AWT and SwingThe AWT and Swing
The AWT and Swing
 
Z blue introduction to gui (39023299)
Z blue   introduction to gui (39023299)Z blue   introduction to gui (39023299)
Z blue introduction to gui (39023299)
 
Swing
SwingSwing
Swing
 
Session 3 J2ME Mobile Information Device Profile(MIDP) API
Session 3 J2ME Mobile Information Device Profile(MIDP)  APISession 3 J2ME Mobile Information Device Profile(MIDP)  API
Session 3 J2ME Mobile Information Device Profile(MIDP) API
 
Gui
GuiGui
Gui
 
Advance Java Programming (CM5I) 1.AWT
Advance Java Programming (CM5I) 1.AWTAdvance Java Programming (CM5I) 1.AWT
Advance Java Programming (CM5I) 1.AWT
 
JavaYDL18
JavaYDL18JavaYDL18
JavaYDL18
 
Swing and Graphical User Interface in Java
Swing and Graphical User Interface in JavaSwing and Graphical User Interface in Java
Swing and Graphical User Interface in Java
 

Semelhante a NSNotificationCenter vs. AppDelegate

Designing for Windows Phone 8
Designing for Windows Phone 8Designing for Windows Phone 8
Designing for Windows Phone 8David Isbitski
 
Whoops! Where did my architecture go?
Whoops! Where did my architecture go?Whoops! Where did my architecture go?
Whoops! Where did my architecture go?Oliver Gierke
 
02 programmation mobile - android - (activity, view, fragment)
02 programmation mobile - android - (activity, view, fragment)02 programmation mobile - android - (activity, view, fragment)
02 programmation mobile - android - (activity, view, fragment)TECOS
 
Android Activities.pdf
Android Activities.pdfAndroid Activities.pdf
Android Activities.pdfssusere71a07
 
Mobile Software Engineering Crash Course - C04 Android Cont.
Mobile Software Engineering Crash Course - C04 Android Cont.Mobile Software Engineering Crash Course - C04 Android Cont.
Mobile Software Engineering Crash Course - C04 Android Cont.Mohammad Shaker
 
Gitter marionette deck
Gitter marionette deckGitter marionette deck
Gitter marionette deckMike Bartlett
 
Event handling63
Event handling63Event handling63
Event handling63myrajendra
 
Android development Training Programme Day 2
Android development Training Programme Day 2Android development Training Programme Day 2
Android development Training Programme Day 2DHIRAJ PRAVIN
 
De constructed-module
De constructed-moduleDe constructed-module
De constructed-moduleJames Cowie
 
Exception handling in asp.net
Exception handling in asp.netException handling in asp.net
Exception handling in asp.netNeelesh Shukla
 
iOS app dev Training - Session1
iOS app dev Training - Session1iOS app dev Training - Session1
iOS app dev Training - Session1Hussain Behestee
 
ElixirConf 2019 - Your Guide to Understand the Initial Commit of a Phoenix Pr...
ElixirConf 2019 - Your Guide to Understand the Initial Commit of a Phoenix Pr...ElixirConf 2019 - Your Guide to Understand the Initial Commit of a Phoenix Pr...
ElixirConf 2019 - Your Guide to Understand the Initial Commit of a Phoenix Pr...Jorge Bejar
 
Architecting Single Activity Applications (With or Without Fragments)
Architecting Single Activity Applications (With or Without Fragments)Architecting Single Activity Applications (With or Without Fragments)
Architecting Single Activity Applications (With or Without Fragments)Gabor Varadi
 
Object Oriented Programming With Real-World Scenario
Object Oriented Programming With Real-World ScenarioObject Oriented Programming With Real-World Scenario
Object Oriented Programming With Real-World ScenarioDurgesh Singh
 
Anatomy of android application
Anatomy of android applicationAnatomy of android application
Anatomy of android applicationNikunj Dhameliya
 
Magento 2 Seminar - Anton Kril - Magento 2 Summary
Magento 2 Seminar - Anton Kril - Magento 2 SummaryMagento 2 Seminar - Anton Kril - Magento 2 Summary
Magento 2 Seminar - Anton Kril - Magento 2 SummaryYireo
 

Semelhante a NSNotificationCenter vs. AppDelegate (20)

Designing for Windows Phone 8
Designing for Windows Phone 8Designing for Windows Phone 8
Designing for Windows Phone 8
 
Whoops! Where did my architecture go?
Whoops! Where did my architecture go?Whoops! Where did my architecture go?
Whoops! Where did my architecture go?
 
Exception
ExceptionException
Exception
 
02 programmation mobile - android - (activity, view, fragment)
02 programmation mobile - android - (activity, view, fragment)02 programmation mobile - android - (activity, view, fragment)
02 programmation mobile - android - (activity, view, fragment)
 
Android Activities.pdf
Android Activities.pdfAndroid Activities.pdf
Android Activities.pdf
 
Mobile Software Engineering Crash Course - C04 Android Cont.
Mobile Software Engineering Crash Course - C04 Android Cont.Mobile Software Engineering Crash Course - C04 Android Cont.
Mobile Software Engineering Crash Course - C04 Android Cont.
 
Gitter marionette deck
Gitter marionette deckGitter marionette deck
Gitter marionette deck
 
Event handling63
Event handling63Event handling63
Event handling63
 
Android development Training Programme Day 2
Android development Training Programme Day 2Android development Training Programme Day 2
Android development Training Programme Day 2
 
De constructed-module
De constructed-moduleDe constructed-module
De constructed-module
 
Exception handling in asp.net
Exception handling in asp.netException handling in asp.net
Exception handling in asp.net
 
iOS app dev Training - Session1
iOS app dev Training - Session1iOS app dev Training - Session1
iOS app dev Training - Session1
 
Xam expertday
Xam expertdayXam expertday
Xam expertday
 
ElixirConf 2019 - Your Guide to Understand the Initial Commit of a Phoenix Pr...
ElixirConf 2019 - Your Guide to Understand the Initial Commit of a Phoenix Pr...ElixirConf 2019 - Your Guide to Understand the Initial Commit of a Phoenix Pr...
ElixirConf 2019 - Your Guide to Understand the Initial Commit of a Phoenix Pr...
 
Architecting Single Activity Applications (With or Without Fragments)
Architecting Single Activity Applications (With or Without Fragments)Architecting Single Activity Applications (With or Without Fragments)
Architecting Single Activity Applications (With or Without Fragments)
 
JUNit Presentation
JUNit PresentationJUNit Presentation
JUNit Presentation
 
Object Oriented Programming With Real-World Scenario
Object Oriented Programming With Real-World ScenarioObject Oriented Programming With Real-World Scenario
Object Oriented Programming With Real-World Scenario
 
Code Quality Management iOS
Code Quality Management iOSCode Quality Management iOS
Code Quality Management iOS
 
Anatomy of android application
Anatomy of android applicationAnatomy of android application
Anatomy of android application
 
Magento 2 Seminar - Anton Kril - Magento 2 Summary
Magento 2 Seminar - Anton Kril - Magento 2 SummaryMagento 2 Seminar - Anton Kril - Magento 2 Summary
Magento 2 Seminar - Anton Kril - Magento 2 Summary
 

Mais de John Wilker

Cranking Floating Point Performance Up To 11
Cranking Floating Point Performance Up To 11Cranking Floating Point Performance Up To 11
Cranking Floating Point Performance Up To 11John Wilker
 
Introtoduction to cocos2d
Introtoduction to  cocos2dIntrotoduction to  cocos2d
Introtoduction to cocos2dJohn Wilker
 
Getting Started with OpenGL ES
Getting Started with OpenGL ESGetting Started with OpenGL ES
Getting Started with OpenGL ESJohn Wilker
 
User Input in a multi-touch, accelerometer, location aware world.
User Input in a multi-touch, accelerometer, location aware world.User Input in a multi-touch, accelerometer, location aware world.
User Input in a multi-touch, accelerometer, location aware world.John Wilker
 
Physics Solutions for Innovative Game Design
Physics Solutions for Innovative Game DesignPhysics Solutions for Innovative Game Design
Physics Solutions for Innovative Game DesignJohn Wilker
 
Getting Oriented with MapKit: Everything you need to get started with the new...
Getting Oriented with MapKit: Everything you need to get started with the new...Getting Oriented with MapKit: Everything you need to get started with the new...
Getting Oriented with MapKit: Everything you need to get started with the new...John Wilker
 
Getting Started with iPhone Game Development
Getting Started with iPhone Game DevelopmentGetting Started with iPhone Game Development
Getting Started with iPhone Game DevelopmentJohn Wilker
 
Internationalizing Your Apps
Internationalizing Your AppsInternationalizing Your Apps
Internationalizing Your AppsJohn Wilker
 
Optimizing Data Caching for iPhone Application Responsiveness
Optimizing Data Caching for iPhone Application ResponsivenessOptimizing Data Caching for iPhone Application Responsiveness
Optimizing Data Caching for iPhone Application ResponsivenessJohn Wilker
 
I Phone On Rails
I Phone On RailsI Phone On Rails
I Phone On RailsJohn Wilker
 
Integrating Push Notifications in your iPhone application with iLime
Integrating Push Notifications in your iPhone application with iLimeIntegrating Push Notifications in your iPhone application with iLime
Integrating Push Notifications in your iPhone application with iLimeJohn Wilker
 
Starting Core Animation
Starting Core AnimationStarting Core Animation
Starting Core AnimationJohn Wilker
 
P2P Multiplayer Gaming
P2P Multiplayer GamingP2P Multiplayer Gaming
P2P Multiplayer GamingJohn Wilker
 
Using Concurrency To Improve Responsiveness
Using Concurrency To Improve ResponsivenessUsing Concurrency To Improve Responsiveness
Using Concurrency To Improve ResponsivenessJohn Wilker
 
Leaving Interface Builder Behind
Leaving Interface Builder BehindLeaving Interface Builder Behind
Leaving Interface Builder BehindJohn Wilker
 
Mobile WebKit Development and jQTouch
Mobile WebKit Development and jQTouchMobile WebKit Development and jQTouch
Mobile WebKit Development and jQTouchJohn Wilker
 
Accelerometer and OpenGL
Accelerometer and OpenGLAccelerometer and OpenGL
Accelerometer and OpenGLJohn Wilker
 
Deep Geek Diving into the iPhone OS and Framework
Deep Geek Diving into the iPhone OS and FrameworkDeep Geek Diving into the iPhone OS and Framework
Deep Geek Diving into the iPhone OS and FrameworkJohn Wilker
 
From Flash to iPhone
From Flash to iPhoneFrom Flash to iPhone
From Flash to iPhoneJohn Wilker
 

Mais de John Wilker (20)

Cranking Floating Point Performance Up To 11
Cranking Floating Point Performance Up To 11Cranking Floating Point Performance Up To 11
Cranking Floating Point Performance Up To 11
 
Introtoduction to cocos2d
Introtoduction to  cocos2dIntrotoduction to  cocos2d
Introtoduction to cocos2d
 
Getting Started with OpenGL ES
Getting Started with OpenGL ESGetting Started with OpenGL ES
Getting Started with OpenGL ES
 
User Input in a multi-touch, accelerometer, location aware world.
User Input in a multi-touch, accelerometer, location aware world.User Input in a multi-touch, accelerometer, location aware world.
User Input in a multi-touch, accelerometer, location aware world.
 
Physics Solutions for Innovative Game Design
Physics Solutions for Innovative Game DesignPhysics Solutions for Innovative Game Design
Physics Solutions for Innovative Game Design
 
Getting Oriented with MapKit: Everything you need to get started with the new...
Getting Oriented with MapKit: Everything you need to get started with the new...Getting Oriented with MapKit: Everything you need to get started with the new...
Getting Oriented with MapKit: Everything you need to get started with the new...
 
Getting Started with iPhone Game Development
Getting Started with iPhone Game DevelopmentGetting Started with iPhone Game Development
Getting Started with iPhone Game Development
 
Internationalizing Your Apps
Internationalizing Your AppsInternationalizing Your Apps
Internationalizing Your Apps
 
Optimizing Data Caching for iPhone Application Responsiveness
Optimizing Data Caching for iPhone Application ResponsivenessOptimizing Data Caching for iPhone Application Responsiveness
Optimizing Data Caching for iPhone Application Responsiveness
 
I Phone On Rails
I Phone On RailsI Phone On Rails
I Phone On Rails
 
Integrating Push Notifications in your iPhone application with iLime
Integrating Push Notifications in your iPhone application with iLimeIntegrating Push Notifications in your iPhone application with iLime
Integrating Push Notifications in your iPhone application with iLime
 
Starting Core Animation
Starting Core AnimationStarting Core Animation
Starting Core Animation
 
P2P Multiplayer Gaming
P2P Multiplayer GamingP2P Multiplayer Gaming
P2P Multiplayer Gaming
 
Using Concurrency To Improve Responsiveness
Using Concurrency To Improve ResponsivenessUsing Concurrency To Improve Responsiveness
Using Concurrency To Improve Responsiveness
 
Leaving Interface Builder Behind
Leaving Interface Builder BehindLeaving Interface Builder Behind
Leaving Interface Builder Behind
 
Mobile WebKit Development and jQTouch
Mobile WebKit Development and jQTouchMobile WebKit Development and jQTouch
Mobile WebKit Development and jQTouch
 
Accelerometer and OpenGL
Accelerometer and OpenGLAccelerometer and OpenGL
Accelerometer and OpenGL
 
Deep Geek Diving into the iPhone OS and Framework
Deep Geek Diving into the iPhone OS and FrameworkDeep Geek Diving into the iPhone OS and Framework
Deep Geek Diving into the iPhone OS and Framework
 
Using SQLite
Using SQLiteUsing SQLite
Using SQLite
 
From Flash to iPhone
From Flash to iPhoneFrom Flash to iPhone
From Flash to iPhone
 

Último

Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 

Último (20)

Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 

NSNotificationCenter vs. AppDelegate

  • 1. AppDelegate vs. NSNotificationCenter What they are, and some Pros and Cons Kenji Hollis March 03, 2009 WillowTree Consulting Group Tuesday, March 3, 2009
  • 2. What is a Delegate? • An object that acts on events • Generally named “ClassXYZDelegate” • Allows objects to manipulate one-another without the need for inheritance • Used by most Cocoa Touch classes • Should be implemented using formal protocols • Think of them as “callbacks”, most of which are optional. Tuesday, March 3, 2009
  • 3. Target-Action • Target: the delegate class that implements a method to call when an event is performed. • Action: the method that responds to the target event. • Used by UIKit. Example, UIAlertView: set the delegate (target), implement dismissal delegate and respond to the request (action). Tuesday, March 3, 2009
  • 4. Quick “How-To” In your accessor class header: Class .h file: @interface Class { id parentDelegate; } - (id)delegate; - (void)setDelegate:(id)newDelegate; Tuesday, March 3, 2009
  • 5. Quick “How-To” Implement the code in the accessor class: Class .m file: - (id)delegate { return parentDelegate; } - (void)setDelegate:(id)newDelegate { parentDelegate = newDelegate; } Tuesday, March 3, 2009
  • 6. Quick “How-To” Calling a delegate function from the accessor: Class .m file: - (void)performEvent { if ([parentDelegate respondsToSelector:@selector(myEvent)]) { [parentDelegate myEvent]; } } We use “respondsToSelector” to verify that the selector exists in the implementing delegate class. Note the “blind call” to the “myEvent” function. Tuesday, March 3, 2009
  • 7. Quick “How-To” Alternate method: Class .m file: - (void)performEvent { if ([parentDelegate respondsToSelector:@selector(myEvent)]) { [parentDelegate performSelector:@selector(myEvent)]; } } We are calling the selector by using “performSelector” instead of blindly calling the member. Here, “myEvent” is the action, “parentDelegate” is the target. Tuesday, March 3, 2009
  • 8. Delegate Use: • A delegate is called after tapping a line in a UITableView, or tapping a button in a UIAlertView. • Telling the application to switch to a different tab view. • Responding to an application interruption. • Running an operation that may block the application until complete (with a “Please wait” box) Tuesday, March 3, 2009
  • 9. An example delegation Modal Confirmation Dialog button clicked, generates “OK” or “Cancel” action event. “OK” Clicked event “Cancel” Clicked event Display progress pane “Please wait ...” Store “Cancel” result in the DB HTTP Post sent synchronously Close modal dialog to record confirmation Wait for response from the HTTP Post Parse response, store result in DB, close modal dialog and progress pane. Tuesday, March 3, 2009
  • 10. What is an AppDelegate? • Serves as the root controller of your application. • Contains methods to handle application start, shutdown, and interruption. • Contains the setup code for your application’s main window. • Generally knows how to control your application from the top level (ie. change tab bar views, save prefs, etc.) Tuesday, March 3, 2009
  • 11. AppDelegate Example Delegate functions in an example AppDelegate: - (void)applicationDidFinishLaunching:(UIApplication *)app { // ... Set up your code here ... } - (void)function_1 { // ... Do something in the app view controller ... } - (void)function_2 { // ... Manipulate the tab controller here ... } - (void)function_3 { // ... Miscellaneous call here ... } - (void)function_4; - (void)function_5; // ... and on ... and on ... and on... Tuesday, March 3, 2009
  • 12. Calling the AppDelegate members: • First, get access to the AppDelegate by grabbing the [[UIApplication sharedApplication] delegate] object. • Cast that to the application object. • Call the delegate methods where appropriate. Tuesday, March 3, 2009
  • 13. Call the AppDelegate members: - (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)button { // Retrieve the application delegate MyApplication *myApp = (MyApplication *) [[UIApplication sharedApplication] delegate]; // Call the application delegate method. [myApp function_1]; } Tuesday, March 3, 2009
  • 14. Delegate Pros • Function declarations must be strictly defined, or they will not be performed • Delegate functions are almost always guaranteed to fire when the selector is called • Delegates can be reused as often as the programmer sees fit, from several classes • Often used in conjunction with modal operations, so they’re easier to debug • Can be called asynchronously. Tuesday, March 3, 2009
  • 15. Delegate Cons • If a delegate method is not defined properly, it will not be performed, or it may crash the app if called blindly. • If a delegate method signature changes, it has to be changed in all classes that call it. • Because most functions are called synchronously, they can tie up the app if expensive operations are performed. Tuesday, March 3, 2009
  • 16. AppDelegate Pros: • Provide direct access to the application’s view controllers and layout control. • Provide simple, direct access to the root application. • Controls how the application responds to interruptions, startup, and shutdown. This is provided to you by the UIApplicationDelegate protocol. Tuesday, March 3, 2009
  • 17. AppDelegate Overuse: • AppDelegates tend to get filled up with too many member functions, so the AppDelegate turns into a giant mess. • People often use the AppDelegate to get access to their view controller functions. • Miscellaneous functions are often placed in the AppDelegate when they could be otherwise placed in a utility class. Tuesday, March 3, 2009
  • 18. How I’ve used Delegates • Controlled application flow by switching tab views at the application top-level. • Swapped views when the application changes from portrait to landscape mode. • Initialized the application by copying a read- only database into a read/write directory. • Preloaded data from a remote web call on application first load. • The list goes on. Tuesday, March 3, 2009
  • 19. What is a Notification? • A queued message with a payload • Sent application-wide, not to a specific class • Posted “Immediately”, asynchronously, or when convenient to the OS • A single queued message can be received and processed by multiple observers • Can be sent with no registered observers, and your application won’t crash! Tuesday, March 3, 2009
  • 20. Setting up the observer This class receives an event message: Class .m file registering the observer: - (id)init ... { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selector1:) name:@”MY_SELECTOR_1” object:nil]; } - (void)selector1:(NSNotification *)notification { NSObject *obj = [notification object]; if ([obj isKindOfClass:[NSDictionary class]]) { // ... Do dictionary payload functionality here. } else { // ... Perform non-object payload functionality here. } } Tuesday, March 3, 2009
  • 21. Sending the notification This function sends the notification message: Class .m file sending the notification: - (void)myNotifier { [[NSNotificationCenter defaultCenter] postNotificationName:@”MY_SELECTOR_1”]; NSDictionary *myDictionary = [NSDictionary dictionaryWithContentsOfFile:@”myFile.plist”]; [[NSNotificationCenter defaultCenter] postNotificationName:@”MY_SELECTOR_1” object:myDictionary]; } Tuesday, March 3, 2009
  • 22. Don’t forget to deregister! Class .m file registering the observer: - (void)dealloc { [super dealloc]; [[NSNotificationCenter defaultCenter] removeObserver:self name:@”MY_SELECTOR_1” object:nil]; } Note: If you don’t de-register the observer, the class will receive multiple copies of the notification. Tuesday, March 3, 2009
  • 23. Example Notifications • Sending an application-wide status change or refresh message • Notifying the application when a network change occurs • When network data or a packet is received and needs to be processed asynchronously • Sending a message to more than one listener at a time Tuesday, March 3, 2009
  • 25. Notification Flow Notification + Payload Tuesday, March 3, 2009
  • 26. Notification Flow Notification + Payload Tuesday, March 3, 2009
  • 27. Notification Flow Notification NSNotificationCenter + Payload Tuesday, March 3, 2009
  • 28. Notification Flow Notification NSNotificationCenter + Payload Tuesday, March 3, 2009
  • 29. Notification Flow Notification NSNotificationCenter + Payload Observer Tuesday, March 3, 2009
  • 30. Notification Flow Notification NSNotificationCenter + Payload Observer Tuesday, March 3, 2009
  • 31. Notification Flow Notification NSNotificationCenter + Payload Observer Operation(s) Tuesday, March 3, 2009
  • 32. Notification Flow Notification NSNotificationCenter + Payload Observer Operation(s) Tuesday, March 3, 2009
  • 33. Notification Flow Notification NSNotificationCenter + Payload Observer Observer Operation(s) Tuesday, March 3, 2009
  • 34. Notification Flow Notification NSNotificationCenter + Payload Observer Observer Operation(s) Tuesday, March 3, 2009
  • 35. Notification Flow Notification NSNotificationCenter + Payload Observer Observer Observer Operation(s) Tuesday, March 3, 2009
  • 36. Notification Flow Notification NSNotificationCenter + Payload Observer Observer Observer Operation(s) Tuesday, March 3, 2009
  • 37. Notification Flow Notification NSNotificationCenter + Payload Observer Observer Observer Operation(s) Operation(s) Tuesday, March 3, 2009
  • 38. Notification Flow Notification NSNotificationCenter + Payload Observer Observer Observer Operation(s) Operation(s) Tuesday, March 3, 2009
  • 39. Notification Flow Notification NSNotificationCenter + Payload Observer Observer Observer Operation(s) Operation(s) Operation(s) Tuesday, March 3, 2009
  • 40. A real-world example CoreLocationUpdate NSNotificationCenter Observer 1 Observer 2 Observer 3 Hit geonames.org to Store GPS data in Calculate speed and cross-reference GPS SQL database bearing Update label on Update label on screen with data screen with data All of these operations happen asynchronously. Tuesday, March 3, 2009
  • 41. Notification Pros • “Fire and Forget” • A single notification can be processed by multiple listeners • Notifications can be posted to the queue with different “posting styles” or priorities • Notifications can be coalesced so they can be sent in pairs or alphabetically • Almost always used asynchronously. Tuesday, March 3, 2009
  • 42. Notification Cons • If you don’t de-register a handler, you could process a notification message multiple times. (Typically, de-registration is done in the dealloc member function.) • Sending asynchronous notifications can be hard to debug, like threads. • The order in which notifications are received by registered listeners is not guaranteed. Tuesday, March 3, 2009
  • 43. How I’ve used Notifications • Wrote an application-wide CoreLocation wrapper that notifies when location range changes (remember the real-world example?) • Sent notifications to update multiple views when a database change occurred. • Sent notifications when XML lines of data are parsed one-at-a-time. Tuesday, March 3, 2009
  • 44. Delegate + Notification Scenario: • SQL Insert/Update service listens for notifications, with a payload containing insert or update SQL data. • When the SQLUpdate call completes, it fires off a new notification indicating new data has been populated. • A Notification is received, and the affected UITableView then calls “refreshData” and updates itself with the new SQL data, using delegates to populate and refresh itself. Tuesday, March 3, 2009
  • 45. Notification Extras: • You can enqueue notifications using “enqueueNotification” for finer notification control. • You can create your own NSNotificationCenter queue for even finer control. • You can pair notifications up alphabetically or by object for “in order” event firing. Tuesday, March 3, 2009
  • 46. Things to think about... • Cocoa touch uses a large combination of delegates and notification calls. • You can see lots of fun things the UI does by using Categories on the NSNotificationCenter class. • If you end up using NSNotificationCenter in your app, try experimenting with the “enqueueNotification” function for finer grained control. Tuesday, March 3, 2009
  • 47. A Quick Demo!!! • Simple demo that shows NSNotificationCenter being overridden with Categories, so we can see those “fun things” Tuesday, March 3, 2009
  • 48. Thank you! • khollis@willowtreeconsulting.com • http://www.bitgatemobile.com/ • Twitter: @KenjiHollis • kenji.hollis on Skype • 303-521-1864 • Questions or comments? Speak up!! Tuesday, March 3, 2009