SlideShare a Scribd company logo
1 of 65
Download to read offline
KVC/KVO and
                 Bindings
               quot;MVC with less codequot;




CocoaHeads México
   27-Nov-2008


                                      1
Key Value Coding



                   2
What is it?

• Access properties by name:



• Every class essentially becomes a
  dictionary
• Not a 'trick'. This is fundamental
  Cocoa programming.


                                       3
What is it?

    • Access properties by name:
[person name]
[person setName:@quot;Sergioquot;]



    • Every class essentially becomes a
        dictionary
    • Not a 'trick'. This is fundamental
        Cocoa programming.


                                           3
What is it?

    • Access properties by name:
[person name]                [person valueForKey:@quot;namequot;]
[person setName:@quot;Sergioquot;]   [person setValue:@quot;Sergioquot;
                             forKey:@quot;namequot;]


    • Every class essentially becomes a
        dictionary
    • Not a 'trick'. This is fundamental
        Cocoa programming.


                                                            3
How it works
• NSKeyValueCoding
  (informal) protocol

• Implemented by
  NSObject


• NSKeyValueCoding.h



                        4
Using key value coding




                         5
Code!
Using key value coding




                         5
Accessor lookup




                  6
Accessor lookup
1. Search for a public accessor
   ('getLastName' or 'lastName')




                                   6
Accessor lookup
1. Search for a public accessor
   ('getLastName' or 'lastName')
2. If not found, search for a private
   accessor method based on key
   ('_getLastName' or '_lastName').




                                        6
Accessor lookup
1. Search for a public accessor
   ('getLastName' or 'lastName')
2. If not found, search for a private
   accessor method based on key
   ('_getLastName' or '_lastName').
3. If not found' search for an instance
   variable (_lastName or lastName)




                                          6
Accessor lookup
1. Search for a public accessor
   ('getLastName' or 'lastName')
2. If not found, search for a private
   accessor method based on key
   ('_getLastName' or '_lastName').
3. If not found' search for an instance
   variable (_lastName or lastName)
4. If not found, invoke
  valueForUndefinedKey:

                                          6
No magic!



• KVC uses the runtime information
  generated by the compiler
• Easy to fake...




                                     7
quot;Implementingquot; KVC quot;from scratchquot;




                                    8
Code!
quot;Implementingquot; KVC quot;from scratchquot;




                                    8
Performance?


• Every Objective-C message goes
  through objc_msgSend() anyways
• KVC caches property lookups
• Not likely to be the bottleneck



                                    9
KVC, value types and nil

• Property values are always of type id
  (reference type)
  • structs ➔ NSValue
  • numbers ➔ NSNumber
• You should implement
  setNilValueForKey:




                                          10
NSDictionary KVC

• NSDictionary has a custom
  implementation of KVC that
  attempts to match keys against keys
  in the dictionary.

NSDictionary *dictionary;
[dictionary setValue:@quot;Sergioquot; forKey:@quot;namequot;];




                                                  11
Practical uses of KVC



• Used by UI bindigs
• Key-based archiving (serialization)




                                        12
More on KVC



              13
Model Validation

• Optional set of validation methods
• Some views call automatically the
  validation methods
  • Important!: You are not supposed to
    reject the value in setValue:forKey:
  • validateValue:forKey:error:
    automatically calls:
    validate{property}:error:


                                           14
Key Paths

• Like file paths (/usr/local/bin)
• Used to traverse an object graph:
  ”document.header.title”
• valueForKeyPath:,
  setValue:forKeyPath:

• Warning!: you cannot pass a keyPath
  if the selector is just 'forKey:' only to
  'forKeyPath:'


                                              15
Using key paths




                  16
Code!
Using key paths




                  16
KVC and Array properties


• No native support. You cannot pass
  indexes in key paths:
  • valueForKeyPath:@quot;order.items[1].pricequot;
• Ask an array for a key, the array will
  ask all its elements and return an
  array of the resulting values.



                                              17
Set and array operators
• Arrays and sets support ‘aggregate’ keys:
  • @avg, @count, @max, @min, @sum,
      @distinctUnionOfArrays,
      @distinctUnionOfObjects, @distinctUnionOfSets,
      @unionOfArrays, @unionOfObjects, @unionOfSets

• You can use this aggregate properties to bind
   to in IB


NSNumber *total = [purchaseOrder valueForKeyPath: @quot;@sum.pricequot;];




                                                                    18
NSPredicates

    • You can build NSPredicates to use
       more complex queries, like And, Or,
       RegExps, method calling, etc.
    • Cocoa's 'LINQ'
NSArray *severalObjects = [NSArray arrayWithObjects:@quot;Stigquot;,
@quot;Shaffiqquot;, @quot;Chrisquot;, nil];

NSPredicate *predicate = [NSPredicate
predicateWithFormat:@quot;SELF IN %@quot;, severalObjects];

BOOL result = [predicate evaluateWithObject:@quot;Shaffiqquot;];


                                                               19
The secret to KVC
  compliance...




                    20
The secret to KVC
  compliance...


  Just use the correct naming
conventions for your accessors!
   (or Objective-C 2.0 properties)




                                     20
Key Value Observing



                      21
What is it?


• Change notifications to model classes
• Observer pattern
• Based on KVC




                                         22
How it works

• Subscribe:
  • addObserver:forKeyPath:options:context:
  • opitons: NSKeyValueObservingOptionOld
     NSKeyValueObservingOptionNew
• Unsubscribe:
  • removeObserver:forKeyPath:
• Receive notification:
  • observeValue:forKeyPath:
          ofObject:change:context:




                                              23
Important!


• Notification works by replacing your
  accessors.
• This means that direct ivar access will
  not produce notifications!




                                            24
Observing with KVO notifications




                                  25
Code!
Observing with KVO notifications




                                  25
Derived properties

• Example: fullName property that
  changes when lastName and firstName
  change
• Implement:
  keyPathsForValuesAffectingValueForKey:,
  and return a set of all the properties
  that affect that keyPath.



                                            26
Manual notifications


• Example: dynamic value that changes
  a lot. Calculated value you only want
  to display at certain times
• willChangeValueForKey:,
  didChangeValueForKey:,
  automaticallyNotifyObserversForKey:




                                          27
Manual notifications and derived
          properties




                                  28
Code!
Manual notifications and derived
          properties




                                  28
Careful!

• addObserver:… does not throw an
  exception when you get the keyPath
  wrong.
• If you observe a path with multiple
  stages, you should observer at every
  level in the path:
  • “document.header.title”


                                         29
Observing Array changes
• Difficult. You can't observe them at all
  • (in KVO, only the property is observed,
    not the value)
• Option 1: mutableArrayValueForKey:
  • Returns a proxy (expensive) that
    sends notifications when modified
• Option 2: Implement all the array-
  related accessors

                                              30
KVC Accessor selector formats
{property}                   memberOf{property}:
set{property}:               intersect{property}:
                             insertObject:in{property}AtIndex:
_set{property}:              insert{property}:atIndexes:
{property}ForKeyPath:        removeObjectFrom{property}AtIndex:
_{property}ForKeyPath:       remove{property}AtIndexes:
get{property}                replaceObjectIn{property}AtIndex:withObject:
_get{property}               replace{property}AtIndexes:with{property}:
is{property}                 add{property}Object:
_is{property}                remove{property}:
validate{property}:error:    remove{property}Object:
countOf{property}            add{property}:
objectIn{property}AtIndex:   getPrimitive{property}
{property}AtIndexes:         primitive{property}
get{property}:range:         setPrimitive{property}:
enumeratorOf{property}


                                                                            31
Observe array element changes
• You can’t. You have to observe each of
  the elements individually
• Solution: NSArrayController
  • Bind the 'contents' property to the
    array of interest and observe the
    path
    arrangedObjects.{propertyName}
  • For insertions and deletions,
    observe the arrangedObjects
    property directly.
                                           32
Uses for KVO?
• Coherence between multiple views
  and a model
• Simplifying flow control
• Simplifying undo implementation
• Any kind of observer, not only UI
  views.
• Binding controllers: NSController and
  NSArrayController   are based on KVO

                                          33
Bindings



           34
What is it?
    “Allows you to establish a mediated
    connection between a view and a piece
    of data, “binding” them such that a
    change in one is reflected in the other”
                     - Cocoa Bindings Programming Topics guide




• Not restricted to 'views' and 'models'.
  General binding mechanism.


                                                                 35
Manual binding

• Call:
  bind:toObject:withKeyPath:options:
  on the ‘view’ object
• The ‘view’ will use KVC/KVO
  • KVC to load the initial values
  • Receives notifications via KVO
  • Changes the ‘model’ with KVC

                                       36
Manual bindings




                  37
Code!
Manual bindings




                  37
Binding Controllers


• Basic binding works without controllers!
• Object controller: dumb wrapper around KVO
• Array Controller: selection proxy for master-
  detail UI, and observing of arrays.
• User Defaults Controller: Simulates KVC/KVO
  compliance!




                                                  38
Bindings in IB




                 39
Code!
Bindings in IB




                 39
(if time permits)



                    40
One more thing...
Value Transformers
     (if time permits)



                         40
Goal: Reduce 'glue' code




                           41
Goal: Reduce 'glue' code

• Example: binding an 'enabled' control
  to a 'false' property




                                          41
Goal: Reduce 'glue' code

• Example: binding an 'enabled' control
  to a 'false' property
• Example: showing an image for a
  string property




                                          41
Goal: Reduce 'glue' code

• Example: binding an 'enabled' control
  to a 'false' property
• Example: showing an image for a
  string property
• Example: handling null values on the
  model



                                          41
Available value
        transformers:
•   NSNegateBooleanTransformer
•   NSIsNilTransformer
•   NSIsNotNilTransformer
•   NSUnarchiveFromDataTransformer
•   NSKeyedUnarchiveFromDataTransformer
• Custom (write your own
    transformer!)


                                          42
Value Transformers




                     43
Code!
Value Transformers




                     43
Resources

• Introduction to Cocoa Bindings Programming Topics
   (Apple)
• Key Value Coding programming guide (Apple)
• Key Value Observing programming guide (Apple)
• Model Object Implementation Guide (Apple)
• Late Night Cocoa episode 35: KVC/KVO with Stefen Frey
• Introduction to Cocoa Bindings by Scott Stevenson
• Cocoa Bindings Wiki page at Cocoadev.com



                                                          44
45
The End

          45

More Related Content

What's hot

Sane Sharding with Akka Cluster
Sane Sharding with Akka ClusterSane Sharding with Akka Cluster
Sane Sharding with Akka Clustermiciek
 
A JIT Smalltalk VM written in itself
A JIT Smalltalk VM written in itselfA JIT Smalltalk VM written in itself
A JIT Smalltalk VM written in itselfESUG
 
What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?Christophe Porteneuve
 
Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015Morris Singer
 
Creating Gradle Plugins - Oredev
Creating Gradle Plugins - OredevCreating Gradle Plugins - Oredev
Creating Gradle Plugins - OredevAnnyce Davis
 
Testing Javascript with Jasmine
Testing Javascript with JasmineTesting Javascript with Jasmine
Testing Javascript with JasmineTim Tyrrell
 
Shrimp: A Rather Practical Example Of Application Development With RESTinio a...
Shrimp: A Rather Practical Example Of Application Development With RESTinio a...Shrimp: A Rather Practical Example Of Application Development With RESTinio a...
Shrimp: A Rather Practical Example Of Application Development With RESTinio a...Yauheni Akhotnikau
 
From framework coupled code to #microservices through #DDD /by @codelytv
From framework coupled code to #microservices through #DDD /by @codelytvFrom framework coupled code to #microservices through #DDD /by @codelytv
From framework coupled code to #microservices through #DDD /by @codelytvCodelyTV
 
Open Source Ajax Solution @OSDC.tw 2009
Open Source Ajax  Solution @OSDC.tw 2009Open Source Ajax  Solution @OSDC.tw 2009
Open Source Ajax Solution @OSDC.tw 2009Robbie Cheng
 
Code generation with javac plugin
Code generation with javac pluginCode generation with javac plugin
Code generation with javac pluginOleksandr Radchykov
 
Practical JavaScript Promises
Practical JavaScript PromisesPractical JavaScript Promises
Practical JavaScript PromisesAsa Kusuma
 
Mobile Open Day: React Native: Crossplatform fast dive
Mobile Open Day: React Native: Crossplatform fast diveMobile Open Day: React Native: Crossplatform fast dive
Mobile Open Day: React Native: Crossplatform fast diveepamspb
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)BoneyGawande
 
From C++ to Objective-C
From C++ to Objective-CFrom C++ to Objective-C
From C++ to Objective-Ccorehard_by
 
Java script – basic auroskills (2)
Java script – basic   auroskills (2)Java script – basic   auroskills (2)
Java script – basic auroskills (2)BoneyGawande
 
Java script Techniques Part I
Java script Techniques Part IJava script Techniques Part I
Java script Techniques Part ILuis Atencio
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptjnewmanux
 
Middy.js - A powerful Node.js middleware framework for your lambdas​
Middy.js - A powerful Node.js middleware framework for your lambdas​ Middy.js - A powerful Node.js middleware framework for your lambdas​
Middy.js - A powerful Node.js middleware framework for your lambdas​ Luciano Mammino
 

What's hot (20)

Sane Sharding with Akka Cluster
Sane Sharding with Akka ClusterSane Sharding with Akka Cluster
Sane Sharding with Akka Cluster
 
A JIT Smalltalk VM written in itself
A JIT Smalltalk VM written in itselfA JIT Smalltalk VM written in itself
A JIT Smalltalk VM written in itself
 
What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?
 
Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015
 
Creating Gradle Plugins - Oredev
Creating Gradle Plugins - OredevCreating Gradle Plugins - Oredev
Creating Gradle Plugins - Oredev
 
Testing Javascript with Jasmine
Testing Javascript with JasmineTesting Javascript with Jasmine
Testing Javascript with Jasmine
 
Input Method Kit
Input Method KitInput Method Kit
Input Method Kit
 
Shrimp: A Rather Practical Example Of Application Development With RESTinio a...
Shrimp: A Rather Practical Example Of Application Development With RESTinio a...Shrimp: A Rather Practical Example Of Application Development With RESTinio a...
Shrimp: A Rather Practical Example Of Application Development With RESTinio a...
 
From framework coupled code to #microservices through #DDD /by @codelytv
From framework coupled code to #microservices through #DDD /by @codelytvFrom framework coupled code to #microservices through #DDD /by @codelytv
From framework coupled code to #microservices through #DDD /by @codelytv
 
Open Source Ajax Solution @OSDC.tw 2009
Open Source Ajax  Solution @OSDC.tw 2009Open Source Ajax  Solution @OSDC.tw 2009
Open Source Ajax Solution @OSDC.tw 2009
 
Full Stack Unit Testing
Full Stack Unit TestingFull Stack Unit Testing
Full Stack Unit Testing
 
Code generation with javac plugin
Code generation with javac pluginCode generation with javac plugin
Code generation with javac plugin
 
Practical JavaScript Promises
Practical JavaScript PromisesPractical JavaScript Promises
Practical JavaScript Promises
 
Mobile Open Day: React Native: Crossplatform fast dive
Mobile Open Day: React Native: Crossplatform fast diveMobile Open Day: React Native: Crossplatform fast dive
Mobile Open Day: React Native: Crossplatform fast dive
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)
 
From C++ to Objective-C
From C++ to Objective-CFrom C++ to Objective-C
From C++ to Objective-C
 
Java script – basic auroskills (2)
Java script – basic   auroskills (2)Java script – basic   auroskills (2)
Java script – basic auroskills (2)
 
Java script Techniques Part I
Java script Techniques Part IJava script Techniques Part I
Java script Techniques Part I
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
 
Middy.js - A powerful Node.js middleware framework for your lambdas​
Middy.js - A powerful Node.js middleware framework for your lambdas​ Middy.js - A powerful Node.js middleware framework for your lambdas​
Middy.js - A powerful Node.js middleware framework for your lambdas​
 

Similar to Intro to Cocoa KVC/KVO and Bindings

A Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpA Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpMichael Girouard
 
ruby on rails pitfalls
ruby on rails pitfallsruby on rails pitfalls
ruby on rails pitfallsRobbin Fan
 
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory CourseRuby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Coursepeter_marklund
 
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
JavaScript Test-Driven Development with Jasmine 2.0 and Karma JavaScript Test-Driven Development with Jasmine 2.0 and Karma
JavaScript Test-Driven Development with Jasmine 2.0 and Karma Christopher Bartling
 
BADCamp 2008 DB Sync
BADCamp 2008 DB SyncBADCamp 2008 DB Sync
BADCamp 2008 DB SyncShaun Haber
 
Checking the Cross-Platform Framework Cocos2d-x
Checking the Cross-Platform Framework Cocos2d-xChecking the Cross-Platform Framework Cocos2d-x
Checking the Cross-Platform Framework Cocos2d-xAndrey Karpov
 
2011-02-03 LA RubyConf Rails3 TDD Workshop
2011-02-03 LA RubyConf Rails3 TDD Workshop2011-02-03 LA RubyConf Rails3 TDD Workshop
2011-02-03 LA RubyConf Rails3 TDD WorkshopWolfram Arnold
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsMike Subelsky
 
Property Wrappers or how Swift decided to become Java
Property Wrappers or how Swift decided to become JavaProperty Wrappers or how Swift decided to become Java
Property Wrappers or how Swift decided to become JavaVincent Pradeilles
 
Beijing Perl Workshop 2008 Hiveminder Secret Sauce
Beijing Perl Workshop 2008 Hiveminder Secret SauceBeijing Perl Workshop 2008 Hiveminder Secret Sauce
Beijing Perl Workshop 2008 Hiveminder Secret SauceJesse Vincent
 
A Re-Introduction to JavaScript
A Re-Introduction to JavaScriptA Re-Introduction to JavaScript
A Re-Introduction to JavaScriptSimon Willison
 
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Rabble .
 
BOF2644 Developing Java EE 7 Scala apps
BOF2644 Developing Java EE 7 Scala appsBOF2644 Developing Java EE 7 Scala apps
BOF2644 Developing Java EE 7 Scala appsPeter Pilgrim
 
Distributed Search in Riak - Integrating Search in a NoSQL Database: Presente...
Distributed Search in Riak - Integrating Search in a NoSQL Database: Presente...Distributed Search in Riak - Integrating Search in a NoSQL Database: Presente...
Distributed Search in Riak - Integrating Search in a NoSQL Database: Presente...Lucidworks
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasminePaulo Ragonha
 
Angular Weekend
Angular WeekendAngular Weekend
Angular WeekendTroy Miles
 
JavaScript from Scratch: Getting Your Feet Wet
JavaScript from Scratch: Getting Your Feet WetJavaScript from Scratch: Getting Your Feet Wet
JavaScript from Scratch: Getting Your Feet WetMichael Girouard
 
Smart Client Development
Smart Client DevelopmentSmart Client Development
Smart Client DevelopmentTamir Khason
 

Similar to Intro to Cocoa KVC/KVO and Bindings (20)

A Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpA Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented Php
 
ruby on rails pitfalls
ruby on rails pitfallsruby on rails pitfalls
ruby on rails pitfalls
 
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory CourseRuby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
 
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
JavaScript Test-Driven Development with Jasmine 2.0 and Karma JavaScript Test-Driven Development with Jasmine 2.0 and Karma
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
 
BADCamp 2008 DB Sync
BADCamp 2008 DB SyncBADCamp 2008 DB Sync
BADCamp 2008 DB Sync
 
Checking the Cross-Platform Framework Cocos2d-x
Checking the Cross-Platform Framework Cocos2d-xChecking the Cross-Platform Framework Cocos2d-x
Checking the Cross-Platform Framework Cocos2d-x
 
2011-02-03 LA RubyConf Rails3 TDD Workshop
2011-02-03 LA RubyConf Rails3 TDD Workshop2011-02-03 LA RubyConf Rails3 TDD Workshop
2011-02-03 LA RubyConf Rails3 TDD Workshop
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web Apps
 
Property Wrappers or how Swift decided to become Java
Property Wrappers or how Swift decided to become JavaProperty Wrappers or how Swift decided to become Java
Property Wrappers or how Swift decided to become Java
 
Beijing Perl Workshop 2008 Hiveminder Secret Sauce
Beijing Perl Workshop 2008 Hiveminder Secret SauceBeijing Perl Workshop 2008 Hiveminder Secret Sauce
Beijing Perl Workshop 2008 Hiveminder Secret Sauce
 
A Re-Introduction to JavaScript
A Re-Introduction to JavaScriptA Re-Introduction to JavaScript
A Re-Introduction to JavaScript
 
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007
 
BOF2644 Developing Java EE 7 Scala apps
BOF2644 Developing Java EE 7 Scala appsBOF2644 Developing Java EE 7 Scala apps
BOF2644 Developing Java EE 7 Scala apps
 
Distributed Search in Riak - Integrating Search in a NoSQL Database: Presente...
Distributed Search in Riak - Integrating Search in a NoSQL Database: Presente...Distributed Search in Riak - Integrating Search in a NoSQL Database: Presente...
Distributed Search in Riak - Integrating Search in a NoSQL Database: Presente...
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
 
Angular Weekend
Angular WeekendAngular Weekend
Angular Weekend
 
JavaScript from Scratch: Getting Your Feet Wet
JavaScript from Scratch: Getting Your Feet WetJavaScript from Scratch: Getting Your Feet Wet
JavaScript from Scratch: Getting Your Feet Wet
 
Smart Client Development
Smart Client DevelopmentSmart Client Development
Smart Client Development
 
Ruby Under The Hood
Ruby Under The HoodRuby Under The Hood
Ruby Under The Hood
 
Checking Bitcoin
 Checking Bitcoin Checking Bitcoin
Checking Bitcoin
 

Recently uploaded

A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 

Recently uploaded (20)

A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 

Intro to Cocoa KVC/KVO and Bindings

  • 1. KVC/KVO and Bindings quot;MVC with less codequot; CocoaHeads México 27-Nov-2008 1
  • 3. What is it? • Access properties by name: • Every class essentially becomes a dictionary • Not a 'trick'. This is fundamental Cocoa programming. 3
  • 4. What is it? • Access properties by name: [person name] [person setName:@quot;Sergioquot;] • Every class essentially becomes a dictionary • Not a 'trick'. This is fundamental Cocoa programming. 3
  • 5. What is it? • Access properties by name: [person name] [person valueForKey:@quot;namequot;] [person setName:@quot;Sergioquot;] [person setValue:@quot;Sergioquot; forKey:@quot;namequot;] • Every class essentially becomes a dictionary • Not a 'trick'. This is fundamental Cocoa programming. 3
  • 6. How it works • NSKeyValueCoding (informal) protocol • Implemented by NSObject • NSKeyValueCoding.h 4
  • 7. Using key value coding 5
  • 10. Accessor lookup 1. Search for a public accessor ('getLastName' or 'lastName') 6
  • 11. Accessor lookup 1. Search for a public accessor ('getLastName' or 'lastName') 2. If not found, search for a private accessor method based on key ('_getLastName' or '_lastName'). 6
  • 12. Accessor lookup 1. Search for a public accessor ('getLastName' or 'lastName') 2. If not found, search for a private accessor method based on key ('_getLastName' or '_lastName'). 3. If not found' search for an instance variable (_lastName or lastName) 6
  • 13. Accessor lookup 1. Search for a public accessor ('getLastName' or 'lastName') 2. If not found, search for a private accessor method based on key ('_getLastName' or '_lastName'). 3. If not found' search for an instance variable (_lastName or lastName) 4. If not found, invoke valueForUndefinedKey: 6
  • 14. No magic! • KVC uses the runtime information generated by the compiler • Easy to fake... 7
  • 17. Performance? • Every Objective-C message goes through objc_msgSend() anyways • KVC caches property lookups • Not likely to be the bottleneck 9
  • 18. KVC, value types and nil • Property values are always of type id (reference type) • structs ➔ NSValue • numbers ➔ NSNumber • You should implement setNilValueForKey: 10
  • 19. NSDictionary KVC • NSDictionary has a custom implementation of KVC that attempts to match keys against keys in the dictionary. NSDictionary *dictionary; [dictionary setValue:@quot;Sergioquot; forKey:@quot;namequot;]; 11
  • 20. Practical uses of KVC • Used by UI bindigs • Key-based archiving (serialization) 12
  • 22. Model Validation • Optional set of validation methods • Some views call automatically the validation methods • Important!: You are not supposed to reject the value in setValue:forKey: • validateValue:forKey:error: automatically calls: validate{property}:error: 14
  • 23. Key Paths • Like file paths (/usr/local/bin) • Used to traverse an object graph: ”document.header.title” • valueForKeyPath:, setValue:forKeyPath: • Warning!: you cannot pass a keyPath if the selector is just 'forKey:' only to 'forKeyPath:' 15
  • 26. KVC and Array properties • No native support. You cannot pass indexes in key paths: • valueForKeyPath:@quot;order.items[1].pricequot; • Ask an array for a key, the array will ask all its elements and return an array of the resulting values. 17
  • 27. Set and array operators • Arrays and sets support ‘aggregate’ keys: • @avg, @count, @max, @min, @sum, @distinctUnionOfArrays, @distinctUnionOfObjects, @distinctUnionOfSets, @unionOfArrays, @unionOfObjects, @unionOfSets • You can use this aggregate properties to bind to in IB NSNumber *total = [purchaseOrder valueForKeyPath: @quot;@sum.pricequot;]; 18
  • 28. NSPredicates • You can build NSPredicates to use more complex queries, like And, Or, RegExps, method calling, etc. • Cocoa's 'LINQ' NSArray *severalObjects = [NSArray arrayWithObjects:@quot;Stigquot;, @quot;Shaffiqquot;, @quot;Chrisquot;, nil]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@quot;SELF IN %@quot;, severalObjects]; BOOL result = [predicate evaluateWithObject:@quot;Shaffiqquot;]; 19
  • 29. The secret to KVC compliance... 20
  • 30. The secret to KVC compliance... Just use the correct naming conventions for your accessors! (or Objective-C 2.0 properties) 20
  • 32. What is it? • Change notifications to model classes • Observer pattern • Based on KVC 22
  • 33. How it works • Subscribe: • addObserver:forKeyPath:options:context: • opitons: NSKeyValueObservingOptionOld NSKeyValueObservingOptionNew • Unsubscribe: • removeObserver:forKeyPath: • Receive notification: • observeValue:forKeyPath: ofObject:change:context: 23
  • 34. Important! • Notification works by replacing your accessors. • This means that direct ivar access will not produce notifications! 24
  • 35. Observing with KVO notifications 25
  • 36. Code! Observing with KVO notifications 25
  • 37. Derived properties • Example: fullName property that changes when lastName and firstName change • Implement: keyPathsForValuesAffectingValueForKey:, and return a set of all the properties that affect that keyPath. 26
  • 38. Manual notifications • Example: dynamic value that changes a lot. Calculated value you only want to display at certain times • willChangeValueForKey:, didChangeValueForKey:, automaticallyNotifyObserversForKey: 27
  • 39. Manual notifications and derived properties 28
  • 40. Code! Manual notifications and derived properties 28
  • 41. Careful! • addObserver:… does not throw an exception when you get the keyPath wrong. • If you observe a path with multiple stages, you should observer at every level in the path: • “document.header.title” 29
  • 42. Observing Array changes • Difficult. You can't observe them at all • (in KVO, only the property is observed, not the value) • Option 1: mutableArrayValueForKey: • Returns a proxy (expensive) that sends notifications when modified • Option 2: Implement all the array- related accessors 30
  • 43. KVC Accessor selector formats {property} memberOf{property}: set{property}: intersect{property}: insertObject:in{property}AtIndex: _set{property}: insert{property}:atIndexes: {property}ForKeyPath: removeObjectFrom{property}AtIndex: _{property}ForKeyPath: remove{property}AtIndexes: get{property} replaceObjectIn{property}AtIndex:withObject: _get{property} replace{property}AtIndexes:with{property}: is{property} add{property}Object: _is{property} remove{property}: validate{property}:error: remove{property}Object: countOf{property} add{property}: objectIn{property}AtIndex: getPrimitive{property} {property}AtIndexes: primitive{property} get{property}:range: setPrimitive{property}: enumeratorOf{property} 31
  • 44. Observe array element changes • You can’t. You have to observe each of the elements individually • Solution: NSArrayController • Bind the 'contents' property to the array of interest and observe the path arrangedObjects.{propertyName} • For insertions and deletions, observe the arrangedObjects property directly. 32
  • 45. Uses for KVO? • Coherence between multiple views and a model • Simplifying flow control • Simplifying undo implementation • Any kind of observer, not only UI views. • Binding controllers: NSController and NSArrayController are based on KVO 33
  • 46. Bindings 34
  • 47. What is it? “Allows you to establish a mediated connection between a view and a piece of data, “binding” them such that a change in one is reflected in the other” - Cocoa Bindings Programming Topics guide • Not restricted to 'views' and 'models'. General binding mechanism. 35
  • 48. Manual binding • Call: bind:toObject:withKeyPath:options: on the ‘view’ object • The ‘view’ will use KVC/KVO • KVC to load the initial values • Receives notifications via KVO • Changes the ‘model’ with KVC 36
  • 51. Binding Controllers • Basic binding works without controllers! • Object controller: dumb wrapper around KVO • Array Controller: selection proxy for master- detail UI, and observing of arrays. • User Defaults Controller: Simulates KVC/KVO compliance! 38
  • 55. One more thing... Value Transformers (if time permits) 40
  • 57. Goal: Reduce 'glue' code • Example: binding an 'enabled' control to a 'false' property 41
  • 58. Goal: Reduce 'glue' code • Example: binding an 'enabled' control to a 'false' property • Example: showing an image for a string property 41
  • 59. Goal: Reduce 'glue' code • Example: binding an 'enabled' control to a 'false' property • Example: showing an image for a string property • Example: handling null values on the model 41
  • 60. Available value transformers: • NSNegateBooleanTransformer • NSIsNilTransformer • NSIsNotNilTransformer • NSUnarchiveFromDataTransformer • NSKeyedUnarchiveFromDataTransformer • Custom (write your own transformer!) 42
  • 63. Resources • Introduction to Cocoa Bindings Programming Topics (Apple) • Key Value Coding programming guide (Apple) • Key Value Observing programming guide (Apple) • Model Object Implementation Guide (Apple) • Late Night Cocoa episode 35: KVC/KVO with Stefen Frey • Introduction to Cocoa Bindings by Scott Stevenson • Cocoa Bindings Wiki page at Cocoadev.com 44
  • 64. 45
  • 65. The End 45