Enviar pesquisa
Carregar
Using Protocol to Refactor
•
1 gostou
•
406 visualizações
Green Chiu
Seguir
使用 Protocol 來重構 (ObjC) @ CocoaHeads Taipei 2017.11.09
Leia menos
Leia mais
Engenharia
Denunciar
Compartilhar
Denunciar
Compartilhar
1 de 28
Baixar agora
Baixar para ler offline
Recomendados
Swift core
Swift core
Yusuke Kita
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
Unity Technologies Japan K.K.
Building Windows Images with Packer
Building Windows Images with Packer
Matt Wrock
MacRuby & RubyMotion - Madridrb May 2012
MacRuby & RubyMotion - Madridrb May 2012
Mark Villacampa
Writing native bindings to node.js in C++
Writing native bindings to node.js in C++
nsm.nikhil
Introduction to Underscore.js
Introduction to Underscore.js
André Faria Gomes
Cassandra UDF and Materialized Views
Cassandra UDF and Materialized Views
Duyhai Doan
Multithreading and Parallelism on iOS [MobOS 2013]
Multithreading and Parallelism on iOS [MobOS 2013]
Kuba Břečka
Mais conteúdo relacionado
Mais procurados
es6
es6
Imran shaikh
FI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS Basics
Petr Dvorak
Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?
Christian Joudrey
iOS 2 - The practical Stuff
iOS 2 - The practical Stuff
Petr Dvorak
Introduction to Underscore.js
Introduction to Underscore.js
David Jacobs
User defined-functions-cassandra-summit-eu-2014
User defined-functions-cassandra-summit-eu-2014
Robert Stupp
How to Write Node.js Module
How to Write Node.js Module
Fred Chien
Node.js Cloud deployment
Node.js Cloud deployment
Nicholas McClay
Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6
Nilesh Jayanandana
【Unity】Scriptable object 入門と活用例
【Unity】Scriptable object 入門と活用例
Unity Technologies Japan K.K.
ARCでめちゃモテiOSプログラマー
ARCでめちゃモテiOSプログラマー
Satoshi Asano
Webエンジニアから見たiOS5
Webエンジニアから見たiOS5
Satoshi Asano
Localforage - fast and simple storage library for JavaScript.
Localforage - fast and simple storage library for JavaScript.
Sergey Romaneko
Automating Kubernetes Environments with Ansible
Automating Kubernetes Environments with Ansible
Timothy Appnel
What's New in ES6 for Web Devs
What's New in ES6 for Web Devs
Rami Sayar
Node.js/io.js Native C++ Addons
Node.js/io.js Native C++ Addons
Chris Barber
Swift와 Objective-C를 함께 쓰는 방법
Swift와 Objective-C를 함께 쓰는 방법
Jung Kim
Packer
Packer
Diego Pacheco
GeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime Web
Bhagaban Behera
Node.js introduction
Node.js introduction
Prasoon Kumar
Mais procurados
(20)
es6
es6
FI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS Basics
Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?
iOS 2 - The practical Stuff
iOS 2 - The practical Stuff
Introduction to Underscore.js
Introduction to Underscore.js
User defined-functions-cassandra-summit-eu-2014
User defined-functions-cassandra-summit-eu-2014
How to Write Node.js Module
How to Write Node.js Module
Node.js Cloud deployment
Node.js Cloud deployment
Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6
【Unity】Scriptable object 入門と活用例
【Unity】Scriptable object 入門と活用例
ARCでめちゃモテiOSプログラマー
ARCでめちゃモテiOSプログラマー
Webエンジニアから見たiOS5
Webエンジニアから見たiOS5
Localforage - fast and simple storage library for JavaScript.
Localforage - fast and simple storage library for JavaScript.
Automating Kubernetes Environments with Ansible
Automating Kubernetes Environments with Ansible
What's New in ES6 for Web Devs
What's New in ES6 for Web Devs
Node.js/io.js Native C++ Addons
Node.js/io.js Native C++ Addons
Swift와 Objective-C를 함께 쓰는 방법
Swift와 Objective-C를 함께 쓰는 방법
Packer
Packer
GeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime Web
Node.js introduction
Node.js introduction
Semelhante a Using Protocol to Refactor
MFF UK - Introduction to iOS
MFF UK - Introduction to iOS
Petr Dvorak
Cocoa Heads Tricity - Design Patterns
Cocoa Heads Tricity - Design Patterns
Maciej Burda
Building stable testing by isolating network layer
Building stable testing by isolating network layer
Jz Chang
Blocks & GCD
Blocks & GCD
rsebbe
iOS App with Parse.com as RESTful Backend
iOS App with Parse.com as RESTful Backend
Stefano Zanetti
TypeScript for Java Developers
TypeScript for Java Developers
Yakov Fain
Desenvolvimento iOS - Aula 4
Desenvolvimento iOS - Aula 4
Saulo Arruda
Javascript Everywhere
Javascript Everywhere
Pascal Rettig
Grand Central Dispatch Design Patterns
Grand Central Dispatch Design Patterns
Robert Brown
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developers
cacois
Hi performance table views with QuartzCore and CoreText
Hi performance table views with QuartzCore and CoreText
Mugunth Kumar
Bring your code to explore the Azure Data Lake: Execute your .NET/Python/R co...
Bring your code to explore the Azure Data Lake: Execute your .NET/Python/R co...
Michael Rys
iPhone dev intro
iPhone dev intro
Vonbo
Beginning to iPhone development
Beginning to iPhone development
Vonbo
Developing iOS REST Applications
Developing iOS REST Applications
lmrei
Objective-C Is Not Java
Objective-C Is Not Java
Chris Adamson
NestJS
NestJS
Wilson Su
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
Igor Bronovskyy
Hujs 总结
Hujs 总结
yiming he
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
e-Legion
Semelhante a Using Protocol to Refactor
(20)
MFF UK - Introduction to iOS
MFF UK - Introduction to iOS
Cocoa Heads Tricity - Design Patterns
Cocoa Heads Tricity - Design Patterns
Building stable testing by isolating network layer
Building stable testing by isolating network layer
Blocks & GCD
Blocks & GCD
iOS App with Parse.com as RESTful Backend
iOS App with Parse.com as RESTful Backend
TypeScript for Java Developers
TypeScript for Java Developers
Desenvolvimento iOS - Aula 4
Desenvolvimento iOS - Aula 4
Javascript Everywhere
Javascript Everywhere
Grand Central Dispatch Design Patterns
Grand Central Dispatch Design Patterns
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developers
Hi performance table views with QuartzCore and CoreText
Hi performance table views with QuartzCore and CoreText
Bring your code to explore the Azure Data Lake: Execute your .NET/Python/R co...
Bring your code to explore the Azure Data Lake: Execute your .NET/Python/R co...
iPhone dev intro
iPhone dev intro
Beginning to iPhone development
Beginning to iPhone development
Developing iOS REST Applications
Developing iOS REST Applications
Objective-C Is Not Java
Objective-C Is Not Java
NestJS
NestJS
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
Hujs 总结
Hujs 总结
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
Último
GENERAL CONDITIONS FOR CONTRACTS OF CIVIL ENGINEERING WORKS
GENERAL CONDITIONS FOR CONTRACTS OF CIVIL ENGINEERING WORKS
Bahzad5
nvidia AI-gtc 2024 partial slide deck.pptx
nvidia AI-gtc 2024 partial slide deck.pptx
jasonsedano2
Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...
Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...
Amil baba
Engineering Mechanics Chapter 5 Equilibrium of a Rigid Body
Engineering Mechanics Chapter 5 Equilibrium of a Rigid Body
AhmadHajasad2
Transforming Process Safety Management: Challenges, Benefits, and Transition ...
Transforming Process Safety Management: Challenges, Benefits, and Transition ...
soginsider
Vertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptx
Vertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptx
LMW Machine Tool Division
Lecture 2 .pdf
Lecture 2 .pdf
abdnazar2003
Litature Review: Research Paper work for Engineering
Litature Review: Research Paper work for Engineering
Manipal Institute of Technology Manipal
Power System electrical and electronics .pptx
Power System electrical and electronics .pptx
MUKULKUMAR210
SATELITE COMMUNICATION UNIT 1 CEC352 REGULATION 2021 PPT BASICS OF SATELITE ....
SATELITE COMMUNICATION UNIT 1 CEC352 REGULATION 2021 PPT BASICS OF SATELITE ....
santhyamuthu1
The relationship between iot and communication technology
The relationship between iot and communication technology
abdulkadirmukarram03
EPE3163_Hydro power stations_Unit2_Lect2.pptx
EPE3163_Hydro power stations_Unit2_Lect2.pptx
JoseeMusabyimana
cloud computing notes for anna university syllabus
cloud computing notes for anna university syllabus
Violet Violet
Test of Significance of Large Samples for Mean = µ.pptx
Test of Significance of Large Samples for Mean = µ.pptx
Home
ASME BPVC 2023 Section I para leer y entender
ASME BPVC 2023 Section I para leer y entender
juancarlos286641
Présentation IIRB 2024 Chloe Dufrane.pdf
Présentation IIRB 2024 Chloe Dufrane.pdf
Institut Technique de la Betterave
Strategies of Urban Morphologyfor Improving Outdoor Thermal Comfort and Susta...
Strategies of Urban Morphologyfor Improving Outdoor Thermal Comfort and Susta...
amrabdallah9
SUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docx
SUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docx
NaveenVerma126
Lecture 4 .pdf
Lecture 4 .pdf
abdnazar2003
UNIT4_ESD_wfffffggggggggggggith_ARM.pptx
UNIT4_ESD_wfffffggggggggggggith_ARM.pptx
realme6igamerr
Último
(20)
GENERAL CONDITIONS FOR CONTRACTS OF CIVIL ENGINEERING WORKS
GENERAL CONDITIONS FOR CONTRACTS OF CIVIL ENGINEERING WORKS
nvidia AI-gtc 2024 partial slide deck.pptx
nvidia AI-gtc 2024 partial slide deck.pptx
Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...
Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...
Engineering Mechanics Chapter 5 Equilibrium of a Rigid Body
Engineering Mechanics Chapter 5 Equilibrium of a Rigid Body
Transforming Process Safety Management: Challenges, Benefits, and Transition ...
Transforming Process Safety Management: Challenges, Benefits, and Transition ...
Vertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptx
Vertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptx
Lecture 2 .pdf
Lecture 2 .pdf
Litature Review: Research Paper work for Engineering
Litature Review: Research Paper work for Engineering
Power System electrical and electronics .pptx
Power System electrical and electronics .pptx
SATELITE COMMUNICATION UNIT 1 CEC352 REGULATION 2021 PPT BASICS OF SATELITE ....
SATELITE COMMUNICATION UNIT 1 CEC352 REGULATION 2021 PPT BASICS OF SATELITE ....
The relationship between iot and communication technology
The relationship between iot and communication technology
EPE3163_Hydro power stations_Unit2_Lect2.pptx
EPE3163_Hydro power stations_Unit2_Lect2.pptx
cloud computing notes for anna university syllabus
cloud computing notes for anna university syllabus
Test of Significance of Large Samples for Mean = µ.pptx
Test of Significance of Large Samples for Mean = µ.pptx
ASME BPVC 2023 Section I para leer y entender
ASME BPVC 2023 Section I para leer y entender
Présentation IIRB 2024 Chloe Dufrane.pdf
Présentation IIRB 2024 Chloe Dufrane.pdf
Strategies of Urban Morphologyfor Improving Outdoor Thermal Comfort and Susta...
Strategies of Urban Morphologyfor Improving Outdoor Thermal Comfort and Susta...
SUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docx
SUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docx
Lecture 4 .pdf
Lecture 4 .pdf
UNIT4_ESD_wfffffggggggggggggith_ARM.pptx
UNIT4_ESD_wfffffggggggggggggith_ARM.pptx
Using Protocol to Refactor
1.
Using Protocol to Refactor 邱志強,
Green Chiu, iOS Developer.
2.
在 iOS ,提到
Protocol 你會想到什什麼?
3.
繼承 ?
4.
Delegation ?
5.
其他 ?
6.
Delegation Pattern • Apple
⼤大量量使⽤用在 CocoaTouch SDK • UITableView, UICollectionView, UIGestureRecognizer and so on. • NSURLSession, StoreKit • 第三⽅方套件
7.
NS-Protocols • 為了了達到特定⽬目的 archive,
copy, enumerate • NSCopying • NSCoding • NSFastEnumeration
8.
繼承 • Objective-C/Swift 不⽀支援多重繼承,但可以實作多個 Protocols •
我們很習慣使⽤用繼承,⼤大部份了了只是為了了部分的 method 或實作 • 可怕的繼承樹 • 在調整後常出現 ”驚喜”
9.
Protocol in Objective-C @protocol
SampleProtocol <NSObject> - (void)sampleMethodA; - (void)sampleMethodB; @optional - (void)sampleOptionalMethod; @end
10.
Protocol 讓⼀一個 class
或 method 知道如何操作物件
11.
The End
12.
重構 • 類似/同樣的程式碼重複出現
13.
Class LocalPlaylistInfo - (void)fetchPlaylistCoverImageWithSize
… { if (…) { … UIImage *image = nil; DBMetaReference *ref = … ; if (ref.sourceType == …) { DBMetaItem *item = …; … } else if (ref.sourceType == …) { MPMediaItem *item = …; image = [item.artwork imageWith …]; } else if (ref.sourceType == LocalDBContextSongSourceTypeStore) { DBMetaItem *item = …; if (!item) { return; } NSString *imageFileURLString = …; void (^imageCallback)(NSString *fileURLString, UIImage *image) = ^(NSString *fileURLString, UIImage *image) { if (image …) { } else if ([NSURL URLWithString:item.photoURL]) { [[KKRadioImageManager sharedImageManager] fetchImageWithURL:… requester:nil callback:^(UIImage *receiveImage, NSError *error) { if (receiveImage) { … } }]; } }; …
14.
Class SongInfoViewModel - (void)loadSongInfo:(LocalSongInfo
*)inSongInfo { if (inSongInfo.type == LocalDBContextSongSourceTypeStore || ...) { DBMetaItem *item = inSongInfo.rawItem; if (inSongInfo.type == LocalDBContextSongSourceTypeStore) { } else { … } self.imageFileURLString = …; void (^imageCallback)(NSString *fileURLString, UIImage *image) = ^void(NSString *fileURLString, UIImage *image){ if (image) { … weakSelf.albumCoverImage = cropImage; } else if ([NSURL URLWithString:item.photoURL]) { [[KKRadioImageManager sharedImageManager] fetchImageWithURL:… requester:nil callback:^(UIImage *receiveImage, NSError *error) { if (receiveImage) { weakSelf.albumCoverImage = … } … }]; } … }; … return; } if (inSongInfo.image) { … } …
15.
Issues • 相似的實作出現在多個地⽅方 • 為了了圖片,View
or Model 載入了了很多 classes/framework
16.
Design Protocol typedef NS_ENUM(NSInteger,
ProvideImageWay) { ProvideImageWayNone = NSNotFound, ProvideImageWayFetchWithURLString = 0, ProvideImageWayGetWithSize, ProvideImageWayGenerateWithCallback }; @protocol LocalItemImageProvider <NSObject> - (ProvideImageWay)getCoverImageWay; - (NSString *)coverURLString; - (UIImage *)coverImageWithSize:(CGSize)inSize; - (void)generateImageWithCallback:(void(^)(UIImage *))inCallback; @end
17.
After implemented - (void)loadSongInfo:(LocalSongInfo
*)inSongInfo { switch ([inSongInfo getCoverImageWay]) { case UPProvideImageWayGetWithSize: self.albumCoverImageView.image = [inSongInfo coverImageWithSize:CGSizeMake(…)]; break; case UPProvideImageWayGenerateWithCallback: { __weak typeof(self) weakSelf = self; [inSongInfo generateImageWithCallback:^(UIImage *image) { weakSelf.albumCoverImageView.image = image; }]; break; } case UPProvideImageWayFetchWithURLString: … break; case UPProvideImageWayNone: … break; } … }
18.
Optimized // UIImageView+LocalItemImageProvider.m - (void)loadImageWithImageProvider:(id<LocalItemImageProvider>)inImageProvider { if
(![inImageProvider conformsToProtocol:@protocol(LocalItemImageProvider)]) { return; } switch ([inImageProvider getCoverImageWay]) { case ProvideImageWayGetWithSize: self.image = [inImageProvider coverImageWithSize:CGSizeMake(44, 44)]; break; case ProvideImageWayGenerateWithCallback: { __weak typeof(self) weakSelf = self; [inImageProvider generateImageWithCallback:^(UIImage *image) { weakSelf.image = image; }]; break; } case ProvideImageWayFetchWithURLString: [self fetchImageWithURLString:[inImageProvider coverURLString]]; break; case ProvideImageWayNone: default: … break; } }
19.
Finally - (void)loadSongInfo:(UPLocalSongInfo *)inSongInfo { [self.albumCoverImageView
loadImageWithImageProvider:inSongInfo]; … }
20.
Besides • 使⽤用 Protocol
讓程式更更容易易被測試 • Mock 物件變得容易易
21.
Testing // UIImageView+LocalItemImageProvider.m - (void)loadImageWithImageProvider:(id<LocalItemImageProvider>)inImageProvider { if
(![inImageProvider conformsToProtocol:@protocol(LocalItemImageProvider)]) { return; } switch ([inImageProvider getCoverImageWay]) { case ProvideImageWayGetWithSize: self.image = [inImageProvider coverImageWithSize:CGSizeMake(44, 44)]; break; case ProvideImageWayGenerateWithCallback: { __weak typeof(self) weakSelf = self; [inImageProvider generateImageWithCallback:^(UIImage *image) { weakSelf.image = image; }]; break; } case ProvideImageWayFetchWithURLString: [self fetchImageWithURLString:[inImageProvider coverURLString]]; break; case ProvideImageWayNone: default: … break; } }
22.
Testing @interface TCDummyLocalImageProvider: NSObject
<LocalItemImageProvider> - (instancetype)initWithType:(ProvideImageWay)inWay; @end @implementation TCDummyLocalImageProvider { ProvideImageWay way; } - (instancetype)initWithType:(ProvideImageWay)inWay { self = [super init]; if (self) { way = inWay; } return self; } - (ProvideImageWay)getCoverImageWay { return way; } ... @end
23.
Testing - (void)testUIImageLoadImageWithImageProvider { UIImageView *imageView
= [[UIImageView alloc] init]; [imageView loadImageWithImageProvider:[NSObject new]]; [imageView loadImageWithImageProvider:[[TCDummyLocalImageProvider alloc] initWithWay:-1000]]; [imageView loadImageWithImageProvider:[[TCDummyLocalImageProvider alloc] initWithWay:ProvideImageWayGetWithSize]]; [imageView loadImageWithImageProvider:[[TCDummyLocalImageProvider alloc] initWithWay:...]]; }
24.
This is Protocol-Oriented Programming
25.
One more thing…
27.
We are hiring iOS
Developer and others
28.
Thanks
Baixar agora