SlideShare a Scribd company logo
Design Patterns in iOS
Neo
Design Pattern in iOS
What Design patterns can we see and use in iOS?
Observer
Delegate & DataSource
Notification
KVC & KVO
Factory
class cluster
Singleton
All you don’t have to do, but you
should try to do.

Using them for flexible, loose-
coupling, reusable, readable
Design Pattern in iOS
Observer
Observers register to notifier and wait broadcast messages to do
something
Delegation & DataSource
[What]

They are same design pattern, delegate to someone to process their jobs.
[Why]

For MVC architecture, this pattern can define nice code architecture for
dispatch job clearly
[When]

Some jobs are not belong some roles, they should to implement it

Ex: View shouldn’t to process business logic or fetch data, it should
delegate to controller or model to do.

Design Pattern in iOS
[How]
Tips:
1. Always delegate(or datasource) and caller
2. Delegate must conform caller’s protocol
3. If protocol is optional, caller must implement introspection
4. Delegate’s attribute always weak (memory leak)
Caller steps:
1. Define what jobs (method) need to delegate (protocol)
2. Define an instance variable to be dynamic type
3. If protocol has @optional, then caller must implement introspection
Delegate steps:
1. Adapt protocol
2. Be the caller’s delegate(assign self to caller’s delegate )
3. Implement protocol method
Design Pattern in iOS
MyCaller.h
MyCaller.m
Design Pattern in iOS
MyDelegate.m
Design Pattern in iOS
delegate
caller
[self.delegate showMeTheMoney]
||
[MyDelegate showMeTheMoney]
MyDelegate0x00
0xFC
0x04
(weak)
MyCaller.m
Design Pattern in iOS
At most of time, we don’t need to make wheel by
ourself
We use this pattern when we establish our library
or refactoring to follow MVC Architecture
Design Pattern in iOS
Notification
[What]

When the observed object events happened, observers will be
notified
[Why]

Loose-coupling between object and object, and keeping to
monitor events and react with it
[When]

Some objects need to know some objects’s events are happened
or not

Ex: network connection canceled and we want to interact with
it.

Design Pattern in iOS
[How]
Tips:
1. Always have a default center to process notification
2. One notify - multi objects
3. Receiver can get any messages
4. Observed object posting notification whatever receiver exist or not
5. Delivering notifications to observer is synchronous
6. Using Notification Queues to deliver notifications asynchronously(FIFO)
establish notification steps:
1. Create a notification default center
2. Register observed/observer object to notification center
3. Using customize/default notification
4. Add method to the notification for waiting trigger
Design Pattern in iOS
Synchronous notification
Register notification and send notification
implement the trigger method
Design Pattern in iOS
remove notification
Output log - It will wait notification return
Design Pattern in iOS
Asynchronous notification(FIFO)
Design Pattern in iOS
Default Notification Name
https://developer.apple.com/library/ios/documentation/
UIKit/Reference/UIApplication_Class/index.html
We can see the notification performed after
MainThread
We use this pattern when object needs to interact
with events, and it’s better than delegation when
there are multi objects need to communication.
Design Pattern in iOS
Design Pattern in iOS
KVC - KVO
[What]

When the observed object changed, observers will be notified.
[Why]

Loose-coupling between object and object, and keeping to
monitor values changed and react with it
[When]

Object need to know some objects’s value changed or not

Ex: An image loaded URL from data (sqlite, coredata, etc),
when data changed, image got notification and do something

KVC: Key Value Coding
KVO: Key Value Observe
https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/KeyValueCoding/Articles/Compliant.html#//
apple_ref/doc/uid/20002172-BAJEAIEE
http://rintarou.dyndns.org/2011/07/22/objective-c-programming-筆記-2/
Design Pattern in iOS
KVC-compliance (See spec.)
Attribute and To-One Relationship Compliance
1. Attribute: Scalar type or C struct
2. To-One: Object
Indexed To-Many Relationship Compliance
1. NSArray
Unordered To-Many Relationship Compliance
1. NSSet
Accessor methods
1. Not only setter & getter, but also other access methods. Ex: Count, removal, etc
2. [receiver setValue: forKeyPath:], [receiver valueForKeyPath:]
KVO-compliance (See spec.)
KVC-compliant

Design Pattern in iOS
[How]
Tips:
1. Instance variable or object need to fit KVC-compliant and KVO-compliant
2. If instance variable doesn’t declare by @property, need to implement
accessor method
3. Trigger mechanism always using accessor method
4. Sometimes need to override accessor method better than default
5. Sending notifications manually can decrease unnecessary notifications
establish KVC-KVO steps:
1. Declare objects or variables
2. Make them be KVC-compliant and KVO-compliant
3. Add observer and observed Objects
4. implement KVO protocol method
Design Pattern in iOS
SecObject.h
common.h
Attribute - scalar type and C struct
Design Pattern in iOS
ViewController.m
Design Pattern in iOS
Implement this protocol method in your observer
Design Pattern in iOS
Design Pattern in iOS
If want to customize accessor methods, then follow
these implementation rules
Default Search Pattern for setValue:forKey:
-> 1. set<Key>:
-> 2. _<key>, _is<Key>, <key>, or is<Key> (if accessInstanceVariablesDirectly returns YES)
-> 3. invokes setValue:forUndefinedKey:
Default Search Pattern for valueForKey:
-> 1. get<Key>, <key>, or is<Key>
-> 2. countOf<Key> and (objectIn<Key>AtIndex:or <key>AtIndexes:) P.S.:(at least will call two methods
when call valueForKey:)
-> 3. countOf<Key>, enumeratorOf<Key>, and memberOf<Key>: (object will send to all methods)
-> 4. _<key>, _is<Key>, <key>, or is<Key> (if accessInstanceVariablesDirectly returns YES)
-> 5. invokes valueForUndefinedKey:
Accessor Search Patterns for Simple Attributes
https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/KeyValueCoding/Articles/
SearchImplementation.html
Design Pattern in iOS
Default search pattern for mutableArrayValueForKey:
-> 1. insertObject:in<Key>AtIndex: and removeObjectFrom<Key>AtIndex:(corresponding
to the NSMutableArray primitive methods insertObject:atIndex: and removeObjectAtIndex:
respectively)
OR
insert<Key>:atIndexes: and remove<Key>AtIndexes: (corresponding to the
NSMutableArray insertObjects:atIndexes: and removeObjectsAtIndexes: methods).
-> 2. At least one insertion method and at least one removal method are found, messages
being sent to the original receiver of mutableArrayValueForKey:.
-> 3. set<Key>:
-> 4. _<key> or <key>(if accessInstanceVariablesDirectly returns YES)
-> 5. invokes setValue:forUndefinedKey:
Accessor Search Pattern for Ordered Collections
Design Pattern in iOS
Design Pattern in iOS
Something important to know
There are Accessor Search Pattern for Unordered Collections and
Accessor Search Pattern for Uniquing Ordered Collections rules,
they are similar to ordered collections.
For improving potential performance problem, official
recommend override step.1 method to fulfill what you want
If attribute is a non-object type, implement setNilValueForKey:
if need to pass Nil to attribute
Collection objects can’t contain nil as a value, instead you can use
NSNull. But dictionar yWithValuesForKeys and
setValuesForKeysWithDictionary will auto translate between
NSNull and nil.
Design Pattern in iOS
Manual send changed notification
benefit: it can minimize triggering notifications or group a
number of changes into a single notification
Design Pattern in iOS
Registering Dependent Keys
some values changed dependent on other values changed, it can
monitor these dependent values together.
For example: fullName is changed dependent on firstName and
lastName
Design Pattern in iOS
Collection Operators - KVC-compliance
Simple Collection Operators
@avg, @count, @max, @min, @sum
Object Operators
1. distinctUnionOfObjects
2. unionOfObjects
3. distinctUnionOfArrays
Design Pattern in iOS
Observer design pattern conclusion in iOS
There are three observer patterns - delegation, KVO, notification
Notification
1. If you want to monitor some events happened or not
2. If you want to broadcast notification to multi objects
KVO
1. If you want to monitor values change and do something
2. If you want to pass through controller to monitor data change -MVVM
delegate
1. You don’t always care object’s statement
2. If object have some jobs need someone to help
Design Pattern in iOS
Class cluster (Factory)
[What]

A mechanism for loose-coupling and good code architecture

[Why]

It can hide the detail of implementation, reusable and more
easier to implement similar but different classes
[When]

There are many classes similar but different

Ex: UIButton has many view’s types, but we just know
UIButtonType and put-in buttonWithType, it will create variety
of button.

Design Pattern in iOS
[How]
Tips:
1. Objects are declared by same class
2. Each one has different implementation details
establish class cluster steps:
1. Design how many types will be implement
2. Move out their same implementation details to superclass
3. establish the method which follows types to create instance
4. Implement superclass or subclass
Design Pattern in iOS
common.h
MyCaller.m
Design Pattern in iOS
MyCallerIsNormalMan.h (inherit from MyCaller)
MyCallerIsNormalMan.m Used it!
Design Pattern in iOS
Singleton
[What]

A mechanism for hold one instance and share everywhere

[Why]

Hold instance statement and more easier to pass instance
statement
[When]

You have to record instance statement in App life-cycle, and you
need to fetch it’s data at many places.

For example: UIApplication have an singleton instance variable
to provide App’s status for developer to fetch App’s information.



Design Pattern in iOS
[How]
Tips:
1. Instance should be really need to stay in all App life-cycle
2. Don’t forget to do lock mechanism (semaphore) to prevent multi-access at
the same time
establish notification steps:
1. Establish a method and build a static instance in it
2. Return the instance to provide other instance to access it
3. Establish lock mechanism
P.S.:
Please using dispatch_once to
avoid duplicate instances and
other lock mechanism, here
just sample code.
Design Pattern in iOS
Conclusion

iOS provides some mechanisms which follow
design pattern to us for complete our task faster, we
should not only use them, but also learn how to
make new one.

All we don’t have to do, but we should try to do.
Thank you

More Related Content

What's hot (20)

PDF
Large-Scale JavaScript Development
Addy Osmani
 
PDF
Intro to iOS Application Architecture
Make School
 
PPTX
PresentationPatterns_v2
Maksym Tolstik
 
PPTX
Angular jS Introduction by Google
ASG
 
PDF
Spring Framework
NexThoughts Technologies
 
PPTX
Mvc4
Muhammad Younis
 
PDF
Building Large Scale Javascript Application
Anis Ahmad
 
PPT
Gnizr Architecture (for developers)
hchen1
 
PPTX
Common ASP.NET Design Patterns - Telerik India DevCon 2013
Steven Smith
 
PDF
Introduction to VIPER Architecture
Hendy Christianto
 
PPT
Java EE revisits design patterns
Alex Theedom
 
PDF
Solid principles, Design Patterns, and Domain Driven Design
Irwansyah Irwansyah
 
PPT
Mvc architecture
Surbhi Panhalkar
 
PDF
jQquerysummit - Large-scale JavaScript Application Architecture
Jiby John
 
ODP
Spring survey
Chris Roeder
 
PDF
Spring MVC Framework
Hùng Nguyễn Huy
 
PPTX
Go f designpatterns 130116024923-phpapp02
Jagath Bandara Senanayaka
 
PPTX
Spring MVC 5 & Hibernate 5 Integration
Majurageerthan Arumugathasan
 
PDF
Clean architecture with ddd layering in php
Leonardo Proietti
 
PPTX
Introduction to Spring Framework
Raveendra R
 
Large-Scale JavaScript Development
Addy Osmani
 
Intro to iOS Application Architecture
Make School
 
PresentationPatterns_v2
Maksym Tolstik
 
Angular jS Introduction by Google
ASG
 
Spring Framework
NexThoughts Technologies
 
Building Large Scale Javascript Application
Anis Ahmad
 
Gnizr Architecture (for developers)
hchen1
 
Common ASP.NET Design Patterns - Telerik India DevCon 2013
Steven Smith
 
Introduction to VIPER Architecture
Hendy Christianto
 
Java EE revisits design patterns
Alex Theedom
 
Solid principles, Design Patterns, and Domain Driven Design
Irwansyah Irwansyah
 
Mvc architecture
Surbhi Panhalkar
 
jQquerysummit - Large-scale JavaScript Application Architecture
Jiby John
 
Spring survey
Chris Roeder
 
Spring MVC Framework
Hùng Nguyễn Huy
 
Go f designpatterns 130116024923-phpapp02
Jagath Bandara Senanayaka
 
Spring MVC 5 & Hibernate 5 Integration
Majurageerthan Arumugathasan
 
Clean architecture with ddd layering in php
Leonardo Proietti
 
Introduction to Spring Framework
Raveendra R
 

Similar to Design Patterns in iOS (20)

KEY
Mac/iOS Design Patterns
Robert Brown
 
PDF
Design Patterns in Cocoa Touch
Eliah Nikans
 
PPT
Pavel_Kravchenko_Mobile Development
Ciklum
 
PDF
Session 7 - Overview of the iOS7 app development architecture
Vu Tran Lam
 
PDF
9 Best Design Patterns in iOS to Develop Powerful iPhone Apps.pdf
Concetto Labs
 
PPTX
9 Best Design Patterns in iOS to Develop Powerful iPhone Apps.pptx
Concetto Labs
 
PDF
Distributing information on iOS
Make School
 
KEY
Objective-C Crash Course for Web Developers
Joris Verbogt
 
PDF
Cocoa Heads Tricity - Design Patterns
Maciej Burda
 
PPTX
Fundamental Design Patterns.pptx
JUNSHIN8
 
PDF
02 objective-c session 2
Amr Elghadban (AmrAngry)
 
ZIP
Day 2
Pat Zearfoss
 
PPTX
Code Quality Management iOS
Arpit Kulsreshtha
 
PPT
JAVA design patterns and Basic OOp concepts
Rahul Malhotra
 
PDF
Swift 2.2 Design Patterns CocoaConf Austin 2016
Carl Brown
 
PDF
Intro to Cocoa KVC/KVO and Bindings
Sergio Acosta
 
PDF
iOS development best practices
Michal Juhas
 
PDF
iOS 101 - Xcode, Objective-C, iOS APIs
Subhransu Behera
 
PDF
Cocoa encyclopedia
Alex Ali
 
PDF
Intro to Obj-C Design Patterns or Or how I learned to be less bad
Haris Amin
 
Mac/iOS Design Patterns
Robert Brown
 
Design Patterns in Cocoa Touch
Eliah Nikans
 
Pavel_Kravchenko_Mobile Development
Ciklum
 
Session 7 - Overview of the iOS7 app development architecture
Vu Tran Lam
 
9 Best Design Patterns in iOS to Develop Powerful iPhone Apps.pdf
Concetto Labs
 
9 Best Design Patterns in iOS to Develop Powerful iPhone Apps.pptx
Concetto Labs
 
Distributing information on iOS
Make School
 
Objective-C Crash Course for Web Developers
Joris Verbogt
 
Cocoa Heads Tricity - Design Patterns
Maciej Burda
 
Fundamental Design Patterns.pptx
JUNSHIN8
 
02 objective-c session 2
Amr Elghadban (AmrAngry)
 
Code Quality Management iOS
Arpit Kulsreshtha
 
JAVA design patterns and Basic OOp concepts
Rahul Malhotra
 
Swift 2.2 Design Patterns CocoaConf Austin 2016
Carl Brown
 
Intro to Cocoa KVC/KVO and Bindings
Sergio Acosta
 
iOS development best practices
Michal Juhas
 
iOS 101 - Xcode, Objective-C, iOS APIs
Subhransu Behera
 
Cocoa encyclopedia
Alex Ali
 
Intro to Obj-C Design Patterns or Or how I learned to be less bad
Haris Amin
 
Ad

Recently uploaded (20)

PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PPTX
Comprehensive Guide: Shoviv Exchange to Office 365 Migration Tool 2025
Shoviv Software
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PDF
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
DOCX
Import Data Form Excel to Tally Services
Tally xperts
 
PDF
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
PPTX
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
PPTX
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
PPTX
Human Resources Information System (HRIS)
Amity University, Patna
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PPTX
Revolutionizing Code Modernization with AI
KrzysztofKkol1
 
PDF
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
PDF
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
PPTX
How Apagen Empowered an EPC Company with Engineering ERP Software
SatishKumar2651
 
PDF
Salesforce CRM Services.VALiNTRY360
VALiNTRY360
 
PDF
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
PDF
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
Comprehensive Guide: Shoviv Exchange to Office 365 Migration Tool 2025
Shoviv Software
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
Import Data Form Excel to Tally Services
Tally xperts
 
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
Human Resources Information System (HRIS)
Amity University, Patna
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
Revolutionizing Code Modernization with AI
KrzysztofKkol1
 
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
How Apagen Empowered an EPC Company with Engineering ERP Software
SatishKumar2651
 
Salesforce CRM Services.VALiNTRY360
VALiNTRY360
 
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
Ad

Design Patterns in iOS

  • 2. Design Pattern in iOS What Design patterns can we see and use in iOS? Observer Delegate & DataSource Notification KVC & KVO Factory class cluster Singleton All you don’t have to do, but you should try to do.
 Using them for flexible, loose- coupling, reusable, readable
  • 3. Design Pattern in iOS Observer Observers register to notifier and wait broadcast messages to do something Delegation & DataSource [What]
 They are same design pattern, delegate to someone to process their jobs. [Why]
 For MVC architecture, this pattern can define nice code architecture for dispatch job clearly [When]
 Some jobs are not belong some roles, they should to implement it
 Ex: View shouldn’t to process business logic or fetch data, it should delegate to controller or model to do.

  • 4. Design Pattern in iOS [How] Tips: 1. Always delegate(or datasource) and caller 2. Delegate must conform caller’s protocol 3. If protocol is optional, caller must implement introspection 4. Delegate’s attribute always weak (memory leak) Caller steps: 1. Define what jobs (method) need to delegate (protocol) 2. Define an instance variable to be dynamic type 3. If protocol has @optional, then caller must implement introspection Delegate steps: 1. Adapt protocol 2. Be the caller’s delegate(assign self to caller’s delegate ) 3. Implement protocol method
  • 5. Design Pattern in iOS MyCaller.h MyCaller.m
  • 6. Design Pattern in iOS MyDelegate.m
  • 7. Design Pattern in iOS delegate caller [self.delegate showMeTheMoney] || [MyDelegate showMeTheMoney] MyDelegate0x00 0xFC 0x04 (weak) MyCaller.m
  • 8. Design Pattern in iOS At most of time, we don’t need to make wheel by ourself We use this pattern when we establish our library or refactoring to follow MVC Architecture
  • 9. Design Pattern in iOS Notification [What]
 When the observed object events happened, observers will be notified [Why]
 Loose-coupling between object and object, and keeping to monitor events and react with it [When]
 Some objects need to know some objects’s events are happened or not
 Ex: network connection canceled and we want to interact with it.

  • 10. Design Pattern in iOS [How] Tips: 1. Always have a default center to process notification 2. One notify - multi objects 3. Receiver can get any messages 4. Observed object posting notification whatever receiver exist or not 5. Delivering notifications to observer is synchronous 6. Using Notification Queues to deliver notifications asynchronously(FIFO) establish notification steps: 1. Create a notification default center 2. Register observed/observer object to notification center 3. Using customize/default notification 4. Add method to the notification for waiting trigger
  • 11. Design Pattern in iOS Synchronous notification Register notification and send notification implement the trigger method
  • 12. Design Pattern in iOS remove notification Output log - It will wait notification return
  • 13. Design Pattern in iOS Asynchronous notification(FIFO)
  • 14. Design Pattern in iOS Default Notification Name https://developer.apple.com/library/ios/documentation/ UIKit/Reference/UIApplication_Class/index.html
  • 15. We can see the notification performed after MainThread We use this pattern when object needs to interact with events, and it’s better than delegation when there are multi objects need to communication. Design Pattern in iOS
  • 16. Design Pattern in iOS KVC - KVO [What]
 When the observed object changed, observers will be notified. [Why]
 Loose-coupling between object and object, and keeping to monitor values changed and react with it [When]
 Object need to know some objects’s value changed or not
 Ex: An image loaded URL from data (sqlite, coredata, etc), when data changed, image got notification and do something
 KVC: Key Value Coding KVO: Key Value Observe https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/KeyValueCoding/Articles/Compliant.html#// apple_ref/doc/uid/20002172-BAJEAIEE http://rintarou.dyndns.org/2011/07/22/objective-c-programming-筆記-2/
  • 17. Design Pattern in iOS KVC-compliance (See spec.) Attribute and To-One Relationship Compliance 1. Attribute: Scalar type or C struct 2. To-One: Object Indexed To-Many Relationship Compliance 1. NSArray Unordered To-Many Relationship Compliance 1. NSSet Accessor methods 1. Not only setter & getter, but also other access methods. Ex: Count, removal, etc 2. [receiver setValue: forKeyPath:], [receiver valueForKeyPath:] KVO-compliance (See spec.) KVC-compliant

  • 18. Design Pattern in iOS [How] Tips: 1. Instance variable or object need to fit KVC-compliant and KVO-compliant 2. If instance variable doesn’t declare by @property, need to implement accessor method 3. Trigger mechanism always using accessor method 4. Sometimes need to override accessor method better than default 5. Sending notifications manually can decrease unnecessary notifications establish KVC-KVO steps: 1. Declare objects or variables 2. Make them be KVC-compliant and KVO-compliant 3. Add observer and observed Objects 4. implement KVO protocol method
  • 19. Design Pattern in iOS SecObject.h common.h Attribute - scalar type and C struct
  • 20. Design Pattern in iOS ViewController.m
  • 21. Design Pattern in iOS Implement this protocol method in your observer
  • 23. Design Pattern in iOS If want to customize accessor methods, then follow these implementation rules Default Search Pattern for setValue:forKey: -> 1. set<Key>: -> 2. _<key>, _is<Key>, <key>, or is<Key> (if accessInstanceVariablesDirectly returns YES) -> 3. invokes setValue:forUndefinedKey: Default Search Pattern for valueForKey: -> 1. get<Key>, <key>, or is<Key> -> 2. countOf<Key> and (objectIn<Key>AtIndex:or <key>AtIndexes:) P.S.:(at least will call two methods when call valueForKey:) -> 3. countOf<Key>, enumeratorOf<Key>, and memberOf<Key>: (object will send to all methods) -> 4. _<key>, _is<Key>, <key>, or is<Key> (if accessInstanceVariablesDirectly returns YES) -> 5. invokes valueForUndefinedKey: Accessor Search Patterns for Simple Attributes https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/KeyValueCoding/Articles/ SearchImplementation.html
  • 24. Design Pattern in iOS Default search pattern for mutableArrayValueForKey: -> 1. insertObject:in<Key>AtIndex: and removeObjectFrom<Key>AtIndex:(corresponding to the NSMutableArray primitive methods insertObject:atIndex: and removeObjectAtIndex: respectively) OR insert<Key>:atIndexes: and remove<Key>AtIndexes: (corresponding to the NSMutableArray insertObjects:atIndexes: and removeObjectsAtIndexes: methods). -> 2. At least one insertion method and at least one removal method are found, messages being sent to the original receiver of mutableArrayValueForKey:. -> 3. set<Key>: -> 4. _<key> or <key>(if accessInstanceVariablesDirectly returns YES) -> 5. invokes setValue:forUndefinedKey: Accessor Search Pattern for Ordered Collections
  • 26. Design Pattern in iOS Something important to know There are Accessor Search Pattern for Unordered Collections and Accessor Search Pattern for Uniquing Ordered Collections rules, they are similar to ordered collections. For improving potential performance problem, official recommend override step.1 method to fulfill what you want If attribute is a non-object type, implement setNilValueForKey: if need to pass Nil to attribute Collection objects can’t contain nil as a value, instead you can use NSNull. But dictionar yWithValuesForKeys and setValuesForKeysWithDictionary will auto translate between NSNull and nil.
  • 27. Design Pattern in iOS Manual send changed notification benefit: it can minimize triggering notifications or group a number of changes into a single notification
  • 28. Design Pattern in iOS Registering Dependent Keys some values changed dependent on other values changed, it can monitor these dependent values together. For example: fullName is changed dependent on firstName and lastName
  • 29. Design Pattern in iOS Collection Operators - KVC-compliance Simple Collection Operators @avg, @count, @max, @min, @sum Object Operators 1. distinctUnionOfObjects 2. unionOfObjects 3. distinctUnionOfArrays
  • 30. Design Pattern in iOS Observer design pattern conclusion in iOS There are three observer patterns - delegation, KVO, notification Notification 1. If you want to monitor some events happened or not 2. If you want to broadcast notification to multi objects KVO 1. If you want to monitor values change and do something 2. If you want to pass through controller to monitor data change -MVVM delegate 1. You don’t always care object’s statement 2. If object have some jobs need someone to help
  • 31. Design Pattern in iOS Class cluster (Factory) [What]
 A mechanism for loose-coupling and good code architecture
 [Why]
 It can hide the detail of implementation, reusable and more easier to implement similar but different classes [When]
 There are many classes similar but different
 Ex: UIButton has many view’s types, but we just know UIButtonType and put-in buttonWithType, it will create variety of button.

  • 32. Design Pattern in iOS [How] Tips: 1. Objects are declared by same class 2. Each one has different implementation details establish class cluster steps: 1. Design how many types will be implement 2. Move out their same implementation details to superclass 3. establish the method which follows types to create instance 4. Implement superclass or subclass
  • 33. Design Pattern in iOS common.h MyCaller.m
  • 34. Design Pattern in iOS MyCallerIsNormalMan.h (inherit from MyCaller) MyCallerIsNormalMan.m Used it!
  • 35. Design Pattern in iOS Singleton [What]
 A mechanism for hold one instance and share everywhere
 [Why]
 Hold instance statement and more easier to pass instance statement [When]
 You have to record instance statement in App life-cycle, and you need to fetch it’s data at many places.
 For example: UIApplication have an singleton instance variable to provide App’s status for developer to fetch App’s information.
 

  • 36. Design Pattern in iOS [How] Tips: 1. Instance should be really need to stay in all App life-cycle 2. Don’t forget to do lock mechanism (semaphore) to prevent multi-access at the same time establish notification steps: 1. Establish a method and build a static instance in it 2. Return the instance to provide other instance to access it 3. Establish lock mechanism P.S.: Please using dispatch_once to avoid duplicate instances and other lock mechanism, here just sample code.
  • 37. Design Pattern in iOS Conclusion
 iOS provides some mechanisms which follow design pattern to us for complete our task faster, we should not only use them, but also learn how to make new one.
 All we don’t have to do, but we should try to do.