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
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
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
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
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
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.