SlideShare a Scribd company logo
1 of 38
Download to read offline
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

PresentationPatterns_v2
PresentationPatterns_v2PresentationPatterns_v2
PresentationPatterns_v2
Maksym Tolstik
 

What's hot (20)

Large-Scale JavaScript Development
Large-Scale JavaScript DevelopmentLarge-Scale JavaScript Development
Large-Scale JavaScript Development
 
Intro to iOS Application Architecture
Intro to iOS Application ArchitectureIntro to iOS Application Architecture
Intro to iOS Application Architecture
 
PresentationPatterns_v2
PresentationPatterns_v2PresentationPatterns_v2
PresentationPatterns_v2
 
Viper architecture
Viper architectureViper architecture
Viper architecture
 
Angular jS Introduction by Google
Angular jS Introduction by GoogleAngular jS Introduction by Google
Angular jS Introduction by Google
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
 
Mvc4
Mvc4Mvc4
Mvc4
 
Building Large Scale Javascript Application
Building Large Scale Javascript ApplicationBuilding Large Scale Javascript Application
Building Large Scale Javascript Application
 
Gnizr Architecture (for developers)
Gnizr Architecture (for developers)Gnizr Architecture (for developers)
Gnizr Architecture (for developers)
 
Common ASP.NET Design Patterns - Telerik India DevCon 2013
Common ASP.NET Design Patterns - Telerik India DevCon 2013Common ASP.NET Design Patterns - Telerik India DevCon 2013
Common ASP.NET Design Patterns - Telerik India DevCon 2013
 
Introduction to VIPER Architecture
Introduction to VIPER ArchitectureIntroduction to VIPER Architecture
Introduction to VIPER Architecture
 
Java EE revisits design patterns
Java EE revisits design patterns Java EE revisits design patterns
Java EE revisits design patterns
 
Solid principles, Design Patterns, and Domain Driven Design
Solid principles, Design Patterns, and Domain Driven DesignSolid principles, Design Patterns, and Domain Driven Design
Solid principles, Design Patterns, and Domain Driven Design
 
Mvc architecture
Mvc architectureMvc architecture
Mvc architecture
 
jQquerysummit - Large-scale JavaScript Application Architecture
jQquerysummit - Large-scale JavaScript Application Architecture jQquerysummit - Large-scale JavaScript Application Architecture
jQquerysummit - Large-scale JavaScript Application Architecture
 
Spring survey
Spring surveySpring survey
Spring survey
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
Go f designpatterns 130116024923-phpapp02
Go f designpatterns 130116024923-phpapp02Go f designpatterns 130116024923-phpapp02
Go f designpatterns 130116024923-phpapp02
 
Spring MVC 5 & Hibernate 5 Integration
Spring MVC 5 & Hibernate 5 IntegrationSpring MVC 5 & Hibernate 5 Integration
Spring MVC 5 & Hibernate 5 Integration
 
Clean architecture with ddd layering in php
Clean architecture with ddd layering in phpClean architecture with ddd layering in php
Clean architecture with ddd layering in php
 

Similar to Design Patterns in iOS

Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity Framework
Akhil Mittal
 
Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@
Alex Borsuk
 
Generic Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity FrameworkGeneric Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity Framework
Akhil Mittal
 
Patterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxPatterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docx
danhaley45372
 
iOS Development: What's New
iOS Development: What's NewiOS Development: What's New
iOS Development: What's New
NascentDigital
 
LearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLLearningMVCWithLINQToSQL
LearningMVCWithLINQToSQL
Akhil Mittal
 

Similar to Design Patterns in iOS (20)

Spring boot
Spring bootSpring boot
Spring boot
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity Framework
 
【Unite 2017 Tokyo】C#ジョブシステムによるモバイルゲームのパフォーマンス向上テクニック
【Unite 2017 Tokyo】C#ジョブシステムによるモバイルゲームのパフォーマンス向上テクニック【Unite 2017 Tokyo】C#ジョブシステムによるモバイルゲームのパフォーマンス向上テクニック
【Unite 2017 Tokyo】C#ジョブシステムによるモバイルゲームのパフォーマンス向上テクニック
 
Introduction to Design Patterns
Introduction to Design PatternsIntroduction to Design Patterns
Introduction to Design Patterns
 
Ios development 2
Ios development 2Ios development 2
Ios development 2
 
iOS 101 - Xcode, Objective-C, iOS APIs
iOS 101 - Xcode, Objective-C, iOS APIsiOS 101 - Xcode, Objective-C, iOS APIs
iOS 101 - Xcode, Objective-C, iOS APIs
 
ASP.NET MVC Best Practices malisa ncube
ASP.NET MVC Best Practices   malisa ncubeASP.NET MVC Best Practices   malisa ncube
ASP.NET MVC Best Practices malisa ncube
 
App Project Planning, by Apple
App Project Planning, by AppleApp Project Planning, by Apple
App Project Planning, by Apple
 
Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@
 
Generic Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity FrameworkGeneric Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity Framework
 
Angular2 with TypeScript
Angular2 with TypeScript Angular2 with TypeScript
Angular2 with TypeScript
 
Patterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxPatterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docx
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Design pattern-presentation
Design pattern-presentationDesign pattern-presentation
Design pattern-presentation
 
iOS Development: What's New
iOS Development: What's NewiOS Development: What's New
iOS Development: What's New
 
LearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLLearningMVCWithLINQToSQL
LearningMVCWithLINQToSQL
 
Introduction of Xcode
Introduction of XcodeIntroduction of Xcode
Introduction of Xcode
 
Ef Poco And Unit Testing
Ef Poco And Unit TestingEf Poco And Unit Testing
Ef Poco And Unit Testing
 
Angular2 with type script
Angular2 with type scriptAngular2 with type script
Angular2 with type script
 
L09 Frameworks
L09 FrameworksL09 Frameworks
L09 Frameworks
 

Recently uploaded

%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Recently uploaded (20)

%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security Program
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 

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.