SlideShare une entreprise Scribd logo
1  sur  35
Télécharger pour lire hors ligne
Designs, patterns and practices
in Object Oriented Programming
for iOS Developers
Who the heck am I?
maciej.burda@me.com
Agenda
• obvious best practices in Obj-C (or at least what I do)
• software design patterns
• In mean time there are some questions waiting for you
The obvious is that which is
never seen until someone
expresses it simply.
Khalil Gibran
Best Practices
#pragma mark - group stuff
CHCamelCaseWordInEnglish
@properties vs iVars
NEON for the performance
Method naming
Examples
- (instancetype)initWithWidth:
(CGFloat)width andHeight:(CGFloat)height;
- (UIView*)taggedView:(NSInteger)tag;
- (void)setT:(NSString *)text
i:(UIImage *)image;
- (void)sendAction:(SEL)aSelector:
(id)anObject :(BOOL)flag;
.Notation or [Brackets]
if (!error)
return success;
Ternary operator
NSInteger value = 5;
result = (value != 0) ? x : y;
int a = 1, b = 2, c = 3, d = 4;
int x = 10, y = 5;
int result = a > b ? x = c > d ? c : d : y;
Design Patterns
- are reusable solutions to common problems
in software design.
!
- They’re templates designed to help you write
code that’s easy to understand and reuse.
!
- They also help you create loosely coupled
code so that you can change or replace
components in your code without too much
of a hassle.
MVC
KVO
Singleton
How to use
?
Singletons in Obj-C
• [NSUserDefaults standardUserDefaults]
• [UIScreen mainScreen]
• [NSFileManager defaultManager]
• [UIApplication sharedApplication]
Façade
• make a software library easier to
use, understand and test, since the
facade has convenient methods for
common tasks;
• make the library more readable, for
the same reason;
• reduce dependencies of outside
code on the inner workings of a
library, since most code uses the
facade, thus allowing more
flexibility in developing the system;
• wrap a poorly designed collection
of APIs with a single well-designed
API (as per task needs).
Strategy
Strategy
• defines a family of algorithms,
• encapsulates each algorithm
• makes the algorithms interchangeable within that
family.
@protocol Strategy <NSObject>
!
@optional
- (void) execute;
!
@end
@interface ConcreteStrategyA : NSObject <Strategy>
{
// ivars for A
}
@end
@implementation ConcreteStrategyA
!
- (void) execute
{
NSLog(@"Called ConcreteStrategyA execute method");
}
!
@end
@interface Context : NSObject
{
id<Strategy> strategy;
}
@property (assign) id<Strategy> strategy;
!
- (void) execute;
!
@end
@implementation Context
!
@synthesize strategy;
!
- (void) execute
{
if ([strategy respondsToSelector:@selector(execute)]) {
[strategy execute];
}
}
!
@end
Decorator (Wrapper, Adapter)
is a design pattern that allows behavior to be
added to an individual object, either statically
or dynamically, without affecting the behavior
of other objects from the same class.
Category
#import "UIImage+Retina4.h"
#import <objc/runtime.h>
!
static Method origImageNamedMethod = nil;
!
@implementation UIImage (Retina4)
!
+ (void)initialize {
origImageNamedMethod = class_getClassMethod(self, @selector(imageNamed:));
method_exchangeImplementations(origImageNamedMethod,
class_getClassMethod(self, @selector(retina4ImageNamed:)));
}
!
+ (UIImage *)retina4ImageNamed:(NSString *)imageName {
NSMutableString *imageNameMutable = [imageName mutableCopy];
NSRange retinaAtSymbol = [imageName rangeOfString:@"@"];
if (retinaAtSymbol.location != NSNotFound) {
[imageNameMutable insertString:@"-568h" atIndex:retinaAtSymbol.location];
} else {
CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
if ([UIScreen mainScreen].scale == 2.f && screenHeight == 568.0f) {
NSRange dot = [imageName rangeOfString:@"."];
if (dot.location != NSNotFound) {
[imageNameMutable insertString:@"-568h@2x" atIndex:dot.location];
} else {
[imageNameMutable appendString:@"-568h@2x"];
}
}
}
NSString *imagePath = [[NSBundle mainBundle] pathForResource:imageNameMutable ofType:@""];
if (imagePath) {
return [UIImage retina4ImageNamed:imageNameMutable];
} else {
return [UIImage retina4ImageNamed:imageName];
}
return nil;
}
!
@end
Delegate
This is an important pattern. Apple uses this approach in most of the UIKit
classes:
UITableView
UITextView
UITextField
UIWebView
UIAlert
UIActionSheet
UICollectionView
UIGestureRecognizer
UIScrollView
UIPickerView
Command
is a behavioral design pattern in which an object is used to represent
and encapsulate all the information needed to call a method at a
later time
NSInvocation
!
NSMethodSignature * mySignature = [NSMutableArray
instanceMethodSignatureForSelector:@selector(addObject:)];
NSInvocation * myInvocation = [NSInvocation
invocationWithMethodSignature:mySignature];
NSString * myString = @"String";
//Next, you would specify which object to send the message to:
!
[myInvocation setTarget:myArray];
//Specify the message you wish to send to that object:
!
[myInvocation setSelector:@selector(addObject:)];
//And fill in any arguments for that method:
!
[myInvocation setArgument:&myString atIndex:2];
//Note that object arguments must be passed by pointer.
!
//At this point, myInvocation is a complete object, describing a message that can be sent. To
actually send the message, you would call:
!
[myInvocation invoke];
An NSInvocation is an Objective-C message rendered
static, that is, it is an action turned into an object.
!
Where to go from that?
Thank you for your attention!
Questions?

Contenu connexe

En vedette

Mobile UI Design Patterns
Mobile UI Design PatternsMobile UI Design Patterns
Mobile UI Design Patternsdanhermes
 
Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#Asim Rais Siddiqui
 
Sensational iOS App Design: First Principles and New Trends for 2012
Sensational iOS App Design: First Principles and New Trends for 2012Sensational iOS App Design: First Principles and New Trends for 2012
Sensational iOS App Design: First Principles and New Trends for 2012Qubop Inc.
 
Cocoa Design Patterns
Cocoa Design PatternsCocoa Design Patterns
Cocoa Design Patternssgleadow
 
Mac/iOS Design Patterns
Mac/iOS Design PatternsMac/iOS Design Patterns
Mac/iOS Design PatternsRobert Brown
 
Design Patterns in iOS
Design Patterns in iOSDesign Patterns in iOS
Design Patterns in iOSYi-Shou Chen
 
iOS Coding Best Practices
iOS Coding Best PracticesiOS Coding Best Practices
iOS Coding Best PracticesJean-Luc David
 

En vedette (8)

Mobile UI Design Patterns
Mobile UI Design PatternsMobile UI Design Patterns
Mobile UI Design Patterns
 
Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#
 
Sensational iOS App Design: First Principles and New Trends for 2012
Sensational iOS App Design: First Principles and New Trends for 2012Sensational iOS App Design: First Principles and New Trends for 2012
Sensational iOS App Design: First Principles and New Trends for 2012
 
Cocoa Design Patterns
Cocoa Design PatternsCocoa Design Patterns
Cocoa Design Patterns
 
iOS Design Patterns
iOS Design PatternsiOS Design Patterns
iOS Design Patterns
 
Mac/iOS Design Patterns
Mac/iOS Design PatternsMac/iOS Design Patterns
Mac/iOS Design Patterns
 
Design Patterns in iOS
Design Patterns in iOSDesign Patterns in iOS
Design Patterns in iOS
 
iOS Coding Best Practices
iOS Coding Best PracticesiOS Coding Best Practices
iOS Coding Best Practices
 

Similaire à Cocoa Heads Tricity - Design Patterns

Hi performance table views with QuartzCore and CoreText
Hi performance table views with QuartzCore and CoreTextHi performance table views with QuartzCore and CoreText
Hi performance table views with QuartzCore and CoreTextMugunth Kumar
 
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)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
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...Fabio Franzini
 
Angular 2 for Java Developers
Angular 2 for Java DevelopersAngular 2 for Java Developers
Angular 2 for Java DevelopersYakov Fain
 
Java - A broad introduction
Java - A broad introductionJava - A broad introduction
Java - A broad introductionBirol Efe
 
Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)
Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)
Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)Sarp Erdag
 
Voorhoede - Front-end architecture
Voorhoede - Front-end architectureVoorhoede - Front-end architecture
Voorhoede - Front-end architectureJasper Moelker
 
Porting legacy apps to Griffon
Porting legacy apps to GriffonPorting legacy apps to Griffon
Porting legacy apps to GriffonJames Williams
 
Eclipse e4 Overview
Eclipse e4 OverviewEclipse e4 Overview
Eclipse e4 OverviewLars Vogel
 
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...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
 
ASP.Net 5 and C# 6
ASP.Net 5 and C# 6ASP.Net 5 and C# 6
ASP.Net 5 and C# 6Andy Butland
 
Using Protocol to Refactor
Using Protocol to Refactor Using Protocol to Refactor
Using Protocol to Refactor Green Chiu
 
Mobile App Development: Primi passi con NativeScript e Angular 2
Mobile App Development: Primi passi con NativeScript e Angular 2Mobile App Development: Primi passi con NativeScript e Angular 2
Mobile App Development: Primi passi con NativeScript e Angular 2Filippo Matteo Riggio
 
Awesome html with ujs, jQuery and coffeescript
Awesome html with ujs, jQuery and coffeescriptAwesome html with ujs, jQuery and coffeescript
Awesome html with ujs, jQuery and coffeescriptAmir Barylko
 
Eclipse 40 - Eclipse Summit Europe 2010
Eclipse 40 - Eclipse Summit Europe 2010Eclipse 40 - Eclipse Summit Europe 2010
Eclipse 40 - Eclipse Summit Europe 2010Lars Vogel
 
iOS best practices
iOS best practicesiOS best practices
iOS best practicesMaxim Vialyx
 
Heroku pop-behind-the-sense
Heroku pop-behind-the-senseHeroku pop-behind-the-sense
Heroku pop-behind-the-senseBen Lin
 

Similaire à Cocoa Heads Tricity - Design Patterns (20)

Gwt.create
Gwt.createGwt.create
Gwt.create
 
Hi performance table views with QuartzCore and CoreText
Hi performance table views with QuartzCore and CoreTextHi performance table views with QuartzCore and CoreText
Hi performance table views with QuartzCore and CoreText
 
Final ppt
Final pptFinal ppt
Final ppt
 
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)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)
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
Angular 2 for Java Developers
Angular 2 for Java DevelopersAngular 2 for Java Developers
Angular 2 for Java Developers
 
Java - A broad introduction
Java - A broad introductionJava - A broad introduction
Java - A broad introduction
 
Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)
Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)
Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)
 
Voorhoede - Front-end architecture
Voorhoede - Front-end architectureVoorhoede - Front-end architecture
Voorhoede - Front-end architecture
 
Porting legacy apps to Griffon
Porting legacy apps to GriffonPorting legacy apps to Griffon
Porting legacy apps to Griffon
 
Eclipse e4 Overview
Eclipse e4 OverviewEclipse e4 Overview
Eclipse e4 Overview
 
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...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...
 
ASP.Net 5 and C# 6
ASP.Net 5 and C# 6ASP.Net 5 and C# 6
ASP.Net 5 and C# 6
 
Using Protocol to Refactor
Using Protocol to Refactor Using Protocol to Refactor
Using Protocol to Refactor
 
Mobile App Development: Primi passi con NativeScript e Angular 2
Mobile App Development: Primi passi con NativeScript e Angular 2Mobile App Development: Primi passi con NativeScript e Angular 2
Mobile App Development: Primi passi con NativeScript e Angular 2
 
Awesome html with ujs, jQuery and coffeescript
Awesome html with ujs, jQuery and coffeescriptAwesome html with ujs, jQuery and coffeescript
Awesome html with ujs, jQuery and coffeescript
 
Eclipse 40 - Eclipse Summit Europe 2010
Eclipse 40 - Eclipse Summit Europe 2010Eclipse 40 - Eclipse Summit Europe 2010
Eclipse 40 - Eclipse Summit Europe 2010
 
iOS best practices
iOS best practicesiOS best practices
iOS best practices
 
Heroku pop-behind-the-sense
Heroku pop-behind-the-senseHeroku pop-behind-the-sense
Heroku pop-behind-the-sense
 

Dernier

cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptrcbcrtm
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 

Dernier (20)

cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.ppt
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Odoo Development Company in India | Devintelle Consulting Service
Odoo Development Company in India | Devintelle Consulting ServiceOdoo Development Company in India | Devintelle Consulting Service
Odoo Development Company in India | Devintelle Consulting Service
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 

Cocoa Heads Tricity - Design Patterns

  • 1. Designs, patterns and practices in Object Oriented Programming for iOS Developers
  • 2. Who the heck am I? maciej.burda@me.com
  • 3. Agenda • obvious best practices in Obj-C (or at least what I do) • software design patterns • In mean time there are some questions waiting for you
  • 4. The obvious is that which is never seen until someone expresses it simply. Khalil Gibran
  • 6. #pragma mark - group stuff
  • 9. NEON for the performance
  • 11. Examples - (instancetype)initWithWidth: (CGFloat)width andHeight:(CGFloat)height; - (UIView*)taggedView:(NSInteger)tag; - (void)setT:(NSString *)text i:(UIImage *)image; - (void)sendAction:(SEL)aSelector: (id)anObject :(BOOL)flag;
  • 14. Ternary operator NSInteger value = 5; result = (value != 0) ? x : y; int a = 1, b = 2, c = 3, d = 4; int x = 10, y = 5; int result = a > b ? x = c > d ? c : d : y;
  • 15. Design Patterns - are reusable solutions to common problems in software design. ! - They’re templates designed to help you write code that’s easy to understand and reuse. ! - They also help you create loosely coupled code so that you can change or replace components in your code without too much of a hassle.
  • 16.
  • 17. MVC
  • 18. KVO
  • 21. Singletons in Obj-C • [NSUserDefaults standardUserDefaults] • [UIScreen mainScreen] • [NSFileManager defaultManager] • [UIApplication sharedApplication]
  • 22.
  • 23. Façade • make a software library easier to use, understand and test, since the facade has convenient methods for common tasks; • make the library more readable, for the same reason; • reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system; • wrap a poorly designed collection of APIs with a single well-designed API (as per task needs).
  • 24.
  • 26. Strategy • defines a family of algorithms, • encapsulates each algorithm • makes the algorithms interchangeable within that family.
  • 27. @protocol Strategy <NSObject> ! @optional - (void) execute; ! @end @interface ConcreteStrategyA : NSObject <Strategy> { // ivars for A } @end @implementation ConcreteStrategyA ! - (void) execute { NSLog(@"Called ConcreteStrategyA execute method"); } ! @end
  • 28. @interface Context : NSObject { id<Strategy> strategy; } @property (assign) id<Strategy> strategy; ! - (void) execute; ! @end @implementation Context ! @synthesize strategy; ! - (void) execute { if ([strategy respondsToSelector:@selector(execute)]) { [strategy execute]; } } ! @end
  • 29. Decorator (Wrapper, Adapter) is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class.
  • 30. Category #import "UIImage+Retina4.h" #import <objc/runtime.h> ! static Method origImageNamedMethod = nil; ! @implementation UIImage (Retina4) ! + (void)initialize { origImageNamedMethod = class_getClassMethod(self, @selector(imageNamed:)); method_exchangeImplementations(origImageNamedMethod, class_getClassMethod(self, @selector(retina4ImageNamed:))); } ! + (UIImage *)retina4ImageNamed:(NSString *)imageName { NSMutableString *imageNameMutable = [imageName mutableCopy]; NSRange retinaAtSymbol = [imageName rangeOfString:@"@"]; if (retinaAtSymbol.location != NSNotFound) { [imageNameMutable insertString:@"-568h" atIndex:retinaAtSymbol.location]; } else { CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height; if ([UIScreen mainScreen].scale == 2.f && screenHeight == 568.0f) { NSRange dot = [imageName rangeOfString:@"."]; if (dot.location != NSNotFound) { [imageNameMutable insertString:@"-568h@2x" atIndex:dot.location]; } else { [imageNameMutable appendString:@"-568h@2x"]; } } } NSString *imagePath = [[NSBundle mainBundle] pathForResource:imageNameMutable ofType:@""]; if (imagePath) { return [UIImage retina4ImageNamed:imageNameMutable]; } else { return [UIImage retina4ImageNamed:imageName]; } return nil; } ! @end
  • 31. Delegate This is an important pattern. Apple uses this approach in most of the UIKit classes: UITableView UITextView UITextField UIWebView UIAlert UIActionSheet UICollectionView UIGestureRecognizer UIScrollView UIPickerView
  • 32. Command is a behavioral design pattern in which an object is used to represent and encapsulate all the information needed to call a method at a later time
  • 33. NSInvocation ! NSMethodSignature * mySignature = [NSMutableArray instanceMethodSignatureForSelector:@selector(addObject:)]; NSInvocation * myInvocation = [NSInvocation invocationWithMethodSignature:mySignature]; NSString * myString = @"String"; //Next, you would specify which object to send the message to: ! [myInvocation setTarget:myArray]; //Specify the message you wish to send to that object: ! [myInvocation setSelector:@selector(addObject:)]; //And fill in any arguments for that method: ! [myInvocation setArgument:&myString atIndex:2]; //Note that object arguments must be passed by pointer. ! //At this point, myInvocation is a complete object, describing a message that can be sent. To actually send the message, you would call: ! [myInvocation invoke]; An NSInvocation is an Objective-C message rendered static, that is, it is an action turned into an object. !
  • 34. Where to go from that?
  • 35. Thank you for your attention! Questions?