Intro to Cocoa KVC/KVO and Bindings

Loading...

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

0 comments

Post a comment

    Post a comment
    Embed Video
    Edit your comment Cancel

    8 Favorites

    Intro to Cocoa KVC/KVO and Bindings - Presentation Transcript

    1. KVC/KVO and Bindings \"MVC with less code\" CocoaHeads México 27-Nov-2008 1
    2. Key Value Coding 2
    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:@\"Sergio\"] • 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:@\"name\"] [person setName:@\"Sergio\"] [person setValue:@\"Sergio\" forKey:@\"name\"] • 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
    8. Code! Using key value coding 5
    9. Accessor lookup 6
    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
    15. \"Implementing\" KVC \"from scratch\" 8
    16. Code! \"Implementing\" KVC \"from scratch\" 8
    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:@\"Sergio\" forKey:@\"name\"]; 11
    20. Practical uses of KVC • Used by UI bindigs • Key-based archiving (serialization) 12
    21. More on KVC 13
    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
    24. Using key paths 16
    25. Code! Using key paths 16
    26. KVC and Array properties • No native support. You cannot pass indexes in key paths: • valueForKeyPath:@\"order.items[1].price\" • 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: @\"@sum.price\"]; 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:@\"Stig\", @\"Shaffiq\", @\"Chris\", nil]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@\"SELF IN %@\", severalObjects]; BOOL result = [predicate evaluateWithObject:@\"Shaffiq\"]; 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
    31. Key Value Observing 21
    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
    49. Manual bindings 37
    50. Code! Manual bindings 37
    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
    52. Bindings in IB 39
    53. Code! Bindings in IB 39
    54. (if time permits) 40
    55. One more thing... Value Transformers (if time permits) 40
    56. Goal: Reduce 'glue' code 41
    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
    61. Value Transformers 43
    62. Code! Value Transformers 43
    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

    + Sergio AcostaSergio Acosta, 2 years ago

    custom

    4960 views, 8 favs, 0 embeds more stats

    Presentation for the CocoaHeads Mexico City's sessi more

    More info about this document

    © All Rights Reserved

    Go to text version

    • Total Views 4960
      • 4960 on SlideShare
      • 0 from embeds
    • Comments 0
    • Favorites 8
    • Downloads 40
    Most viewed embeds

    more

    All embeds

    less

    Flagged as inappropriate Flag as inappropriate
    Flag as inappropriate

    Select your reason for flagging this presentation as inappropriate. If needed, use the feedback form to let us know more details.

    Cancel
    File a copyright complaint
    Having problems? Go to our helpdesk?

    Categories