design patterns in ios

38
Design Patterns in iOS Neo

Upload: yi-shou-chen

Post on 15-Jul-2015

275 views

Category:

Software


0 download

TRANSCRIPT

Design Patterns in iOS

Neo

Design Pattern in iOSWhat 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 iOSObserver

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 itEx: 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 iOSMyCaller.h

MyCaller.m

Design Pattern in iOSMyDelegate.m

Design Pattern in iOS

delegate

caller

[self.delegate showMeTheMoney] ||

[MyDelegate showMeTheMoney]

MyDelegate0x00

0xFC

0x04(weak)

MyCaller.m

Design Pattern in iOSAt 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 iOSNotification

[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 notEx: 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 iOSSynchronous notificationRegister notification and send notification

implement the trigger method

Design Pattern in iOSremove notification

Output log - It will wait notification return

Design Pattern in iOSAsynchronous notification(FIFO)

Design Pattern in iOSDefault 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 iOSKVC - 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 notEx: 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 iOSKVC-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 iOSViewController.m

Design Pattern in iOSImplement this protocol method in your observer

Design Pattern in iOS

Design Pattern in iOSIf 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 iOSSomething 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 iOSManual send changed notification

benefit: it can minimize triggering notifications or group a number of changes into a single notification

Design Pattern in iOSRegistering 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 iOSCollection Operators - KVC-compliance

Simple Collection Operators @avg, @count, @max, @min, @sum

Object Operators 1. distinctUnionOfObjects 2. unionOfObjects 3. distinctUnionOfArrays

Design Pattern in iOSObserver 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 iOSClass 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 differentEx: 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 iOScommon.h

MyCaller.m

Design Pattern in iOSMyCallerIsNormalMan.h (inherit from MyCaller)

MyCallerIsNormalMan.m Used it!

Design Pattern in iOSSingleton

[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 iOSConclusion 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