SlideShare ist ein Scribd-Unternehmen logo
1 von 38
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Large-Scale JavaScript Development
Large-Scale JavaScript DevelopmentLarge-Scale JavaScript Development
Large-Scale JavaScript DevelopmentAddy Osmani
 
Intro to iOS Application Architecture
Intro to iOS Application ArchitectureIntro to iOS Application Architecture
Intro to iOS Application ArchitectureMake School
 
PresentationPatterns_v2
PresentationPatterns_v2PresentationPatterns_v2
PresentationPatterns_v2Maksym Tolstik
 
Angular jS Introduction by Google
Angular jS Introduction by GoogleAngular jS Introduction by Google
Angular jS Introduction by GoogleASG
 
Building Large Scale Javascript Application
Building Large Scale Javascript ApplicationBuilding Large Scale Javascript Application
Building Large Scale Javascript ApplicationAnis Ahmad
 
Gnizr Architecture (for developers)
Gnizr Architecture (for developers)Gnizr Architecture (for developers)
Gnizr Architecture (for developers)hchen1
 
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 2013Steven Smith
 
Introduction to VIPER Architecture
Introduction to VIPER ArchitectureIntroduction to VIPER Architecture
Introduction to VIPER ArchitectureHendy Christianto
 
Java EE revisits design patterns
Java EE revisits design patterns Java EE revisits design patterns
Java EE revisits design patterns Alex Theedom
 
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 DesignIrwansyah Irwansyah
 
jQquerysummit - Large-scale JavaScript Application Architecture
jQquerysummit - Large-scale JavaScript Application Architecture jQquerysummit - Large-scale JavaScript Application Architecture
jQquerysummit - Large-scale JavaScript Application Architecture Jiby John
 
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 phpLeonardo Proietti
 

Was ist angesagt? (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
 

Ähnlich wie 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 FrameworkAkhil Mittal
 
【Unite 2017 Tokyo】C#ジョブシステムによるモバイルゲームのパフォーマンス向上テクニック
【Unite 2017 Tokyo】C#ジョブシステムによるモバイルゲームのパフォーマンス向上テクニック【Unite 2017 Tokyo】C#ジョブシステムによるモバイルゲームのパフォーマンス向上テクニック
【Unite 2017 Tokyo】C#ジョブシステムによるモバイルゲームのパフォーマンス向上テクニックUnity Technologies Japan K.K.
 
Ios development 2
Ios development 2Ios development 2
Ios development 2elnaqah
 
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 APIsSubhransu Behera
 
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 ncubeMalisa Ncube
 
App Project Planning, by Apple
App Project Planning, by AppleApp Project Planning, by Apple
App Project Planning, by AppleFranco Cedillo
 
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 FrameworkAkhil Mittal
 
Angular2 with TypeScript
Angular2 with TypeScript Angular2 with TypeScript
Angular2 with TypeScript Rohit Bishnoi
 
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.docxdanhaley45372
 
Design Patterns
Design PatternsDesign Patterns
Design Patternsimedo.de
 
iOS Development: What's New
iOS Development: What's NewiOS Development: What's New
iOS Development: What's NewNascentDigital
 
LearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLLearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLAkhil Mittal
 
Ef Poco And Unit Testing
Ef Poco And Unit TestingEf Poco And Unit Testing
Ef Poco And Unit TestingJames Phillips
 
Angular2 with type script
Angular2 with type scriptAngular2 with type script
Angular2 with type scriptRavi Mone
 

Ähnlich wie 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
 

Kürzlich hochgeladen

+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
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 

Kürzlich hochgeladen (20)

+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...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 

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.