SlideShare une entreprise Scribd logo
1  sur  80
Télécharger pour lire hors ligne
iOS Gems
Some jewels for your glory box




Kevin O’Neill
Delivery Manager – Mobile
REA Group
twitter: @kevinoneill


This is not a con dential session — please stream, blog, tweet and take pictures :)
Roadmap
•   Enhancing NSArray

•   View size and layout

•   Simple gestures handling

•   Closing thoughts
Enhancing NSArray
NSArray
Great Core Support
But …
It’s verbose
- (NSIndexSet *)indexesOfObjectsWithOptions:
(NSEnumerationOptions)opts passingTest:(BOOL
(^)(id obj, NSUInteger idx, BOOL *stop))
predicate
Difficult to combine
- (NSIndexSet *)indexesOfObjectsAtIndexes:
(NSIndexSet *)indexes options:
(NSEnumerationOptions)opts passingTest:(BOOL
(^)(id obj, NSUInteger idx, BOOL
*stop))predicate;
We Can Do Better
•   Enumeration

•   Filtering

•   Transformation
Enumeration
- (void)each:
    (void (^)(id item))block;

- (void)eachWithIndex:
    (void (^)(id, NSUInteger))block;
Consider carefully
Results by side effect only
Huh?
Enumerations produce no
        ‘value’
They mutate state of the
  world around them
EG
  NSMutableSet *uniqueNames = [NSMutableSet
  set];
[names each: ^ (id name) {
  [uniqueNames addObject:name];
}];
OR
[[view subviews] eachWithIndex:^ (id subview,
NSUInteger position) {
  CGRect cell_frame =
  CGRectMake(subview_width * position,
             0,
             requested_subview_size.width,
             requested_subview_size.height);
Demo
Enumeration
Use and implementation
A for loop may often be a
       better choice
Useful at the tail of
transform operations
Filtering
- (NSArray *)filter:(BOOL (^)(id item))block;

- (NSArray *)pick:(BOOL (^)(id item))block;

- (id)first:(BOOL (^)(id))block;

- (id)last:(BOOL (^)(id))block;
Filter removes matching
         elements
Filter
 NSArray *names = [NSArray arrayWithObjects:
                 @"Kevin", @"Sue", @"Aaron",
                 @"Jack", @"Maddie", nil];

[[names filter:^BOOL(id name) {
  return [name length] < 5;
}] each:^(id name) {
  NSLog(@"%@", name);
}];

"Kevin"
"Aaron"
"Maddie"
Pick selects matching
      elements
Pick
NSArray *names = [NSArray arrayWithObjects:
                  @"Kevin", @"Sue", @"Aaron",
                  @"Jack", @"Maddie", nil];

[[names pick:^BOOL(id name) {
  return [name length] < 5;
}] each:^(id name) {
  NSLog(@"%@", name);
}];

"Sue"
"Jack"
First returns the first
 element matched
First
NSArray *names = [NSArray arrayWithObjects:
                  @"Kevin", @"Sue", @"Aaron",
                  @"Jack", @"Maddie", nil];

NSLog(@"%@", [names first:^BOOL(id name) {
  return [name length] < 5;
}]);

"Sue"
Last returns the last
 element matched
Last
NSArray *names = [NSArray arrayWithObjects:
                  @"Kevin", @"Sue", @"Aaron",
                  @"Jack", @"Maddie", nil];

NSLog(@"%@", [names last:^BOOL(id name) {
  return [name length] < 5;
}]);

"Jack"
Demo
Filter, Pick, First and Last
Use and implementation
Transformation
- (NSArray *)map:(id (^)(id item))block;

- (id)reduce:(id (^)(id current, id item))block
     initial:(id)initial;

- (NSArray *)intersperse:(id (^) (void))separator;
Map applies the block to
    each element
Map
NSArray *names = [NSArray arrayWithObjects:
                  @"Kevin", @"Sue", @"Aaron",
                  @"Jack", @"Maddie", nil];

[[names map:^id(id name) {
  return [NSNumber numberWithInteger:
            [name length]];
}] each:^(id length) {
  NSLog(@"%@", length);
}];

"5"
"3"
"5"
…
Reduce applies the block
to each element passing
     the result along
Reduce
NSArray *names = [NSArray arrayWithObjects:
                  @"Kevin", @"Sue", @"Aaron",
                  @"Jack", @"Maddie", nil];

NSLog(@"%@",
[names reduce:^id(id current, id item) {

  NSInteger result = [current integerValue]
                   + [item length];
  return [NSNumber numberWithInteger:result];

} initial:[NSNumber numberWithInteger:0]]);

"23"
Place the result of the
block between elements
Intersperse
NSArray *names = [NSArray arrayWithObjects:
                  @"Kevin", @"Sue", @"Aaron",
                  @"Jack", @"Maddie", nil];

[[names intersperse:^id(id current, id next) {
  return [current length] > [next length]
           ? @">" : @"<";
}] each:^(id item) {
  NSLog(@"%@", item);
}];

"Kevin"
">"
"Sue"
"<"
…
Demo
Map, Reduce, Intersperse
Use and implementation
View size and layout
How to size and layout
subviews without pain
I have a confession
I’m an interface builder
        muppet
Two methods are key
Two methods are key
- (void)layoutSubviews;
- (CGSize)sizeThatFits:(CGSize)size;
A diversion.
Paired methods.
sizeThatFits: and
layoutSubviews are loosely
          paired
They must be sympathetic
    to one and other
- (void)layoutSubviews;

• Does nothing by default
• Used to position subviews
• Called when the layout is dirty
• Don’t call it manually– I’ve seen to
  many times

• Don’t resize self – I’ve seen to many
  times
- (CGSize)sizeThatFits:
           (CGSize)size;

• Returns current size by default
• Return ‘best’ size to fit given size
• Doesn’t resize the view
• Don’t resize the view – I’ve seen to
  many times

• Don’t layout view – I’ve seen to many
  times
But here’s the rub
The calculations used are
  often the same, just
   applied differently
EG
    - (CGSize)sizeThatFits:(CGSize)size;
{
    float width = size.width;

    float height = [[[self subviews] reduce: ^ id (id current, id item) {
      CGSize item_size = [item sizeThatFits:CGSizeMake(width, 0.)];

     return [NSNumber numberWithFloat:
                               ceilf([current floatValue] +
                               (item_size.height + [self spacingForSubview:item]))];

    } initial:[NSNumber numberWithFloat:0.]] floatValue];

    CGSize result = CGSizeMake(width, height);

    return result;
}
And
    - (void)layoutSubviews;
{
    float width = [self width];

    __block StackedView *block_self = self;

    [[self subviews] reduce: ^ id (id current, id item) {
      CGSize item_size = [item sizeThatFits:CGSizeMake(width, 0.)];

      [item setFrame:
               CGRectMake(0,
               [current floatValue] + [block_self spacingForSubview:item],
               item_size.width,
               item_size.height)];

      return [NSNumber numberWithFloat:ceilf([item bottom])];
    } initial:[NSNumber numberWithFloat:0.]];
}
The only real variance here
       is the action
And that’s a simple
     example
We can do better
Demo
Size and Layout
The layout algorithm is
     coded once
Then applied appropriately
Simple gestures handling
Gesture recognisers rock
But maintaining pairing
 between selectors and
actions is a little tedious
EG
    - (void)cancelRequest
{
    [self displayCancelMessage];
}

UITapGestureRecognizer *tapRecognizer =
  [[UITapGestureRecognizer alloc]
    initWithTarget:self
            action:@selector(cancelRequest)];
We can do better
Can you guess what makes
 gesture handling easier?
Demo
Gesture recognisers
Blocks make gesture setup
       much easier
Closing thoughts
Take from this what you will
Understanding blocks will
make you more productive
New Core API’s are taking
  advantage of blocks
So should you
Categories are a key
method of partitioning
     behaviour
Blocks are a key method of
  partitioning algorithms
Associated objects should
  be part of your toolkit
But
Don’t use these tools
because they are there
Use them to make your
       code …
Simpler
Easier to maintain
Useful Bits

Open source libraries used
https://github.com/kevinoneill/Useful-Bits
https://github.com/kevinoneill/Useful-Swipe
https://github.com/domesticcatsoftware/DCIntrospect




Questions?

Contenu connexe

Tendances

Backbone.js Simple Tutorial
Backbone.js Simple TutorialBackbone.js Simple Tutorial
Backbone.js Simple Tutorial
추근 문
 

Tendances (20)

Python speleology
Python speleologyPython speleology
Python speleology
 
MongoDB With Style
MongoDB With StyleMongoDB With Style
MongoDB With Style
 
The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196
 
The Ring programming language version 1.3 book - Part 34 of 88
The Ring programming language version 1.3 book - Part 34 of 88The Ring programming language version 1.3 book - Part 34 of 88
The Ring programming language version 1.3 book - Part 34 of 88
 
究極のコントローラを目指す
究極のコントローラを目指す究極のコントローラを目指す
究極のコントローラを目指す
 
The Ring programming language version 1.5.4 book - Part 44 of 185
The Ring programming language version 1.5.4 book - Part 44 of 185The Ring programming language version 1.5.4 book - Part 44 of 185
The Ring programming language version 1.5.4 book - Part 44 of 185
 
The Ring programming language version 1.5 book - Part 8 of 31
The Ring programming language version 1.5 book - Part 8 of 31The Ring programming language version 1.5 book - Part 8 of 31
The Ring programming language version 1.5 book - Part 8 of 31
 
jQuery
jQueryjQuery
jQuery
 
2013-03-23 - NoSQL Spartakiade
2013-03-23 - NoSQL Spartakiade2013-03-23 - NoSQL Spartakiade
2013-03-23 - NoSQL Spartakiade
 
Patterns for slick database applications
Patterns for slick database applicationsPatterns for slick database applications
Patterns for slick database applications
 
Spock and Geb
Spock and GebSpock and Geb
Spock and Geb
 
Backbone.js Simple Tutorial
Backbone.js Simple TutorialBackbone.js Simple Tutorial
Backbone.js Simple Tutorial
 
The Ring programming language version 1.7 book - Part 57 of 196
The Ring programming language version 1.7 book - Part 57 of 196The Ring programming language version 1.7 book - Part 57 of 196
The Ring programming language version 1.7 book - Part 57 of 196
 
Building DSLs with Groovy
Building DSLs with GroovyBuilding DSLs with Groovy
Building DSLs with Groovy
 
Autopsy Of A Widget
Autopsy Of A WidgetAutopsy Of A Widget
Autopsy Of A Widget
 
supporting t-sql scripts for Heap vs clustered table
supporting t-sql scripts for Heap vs clustered tablesupporting t-sql scripts for Heap vs clustered table
supporting t-sql scripts for Heap vs clustered table
 
OSDC.fr 2012 :: Cascalog : progammation logique pour Hadoop
OSDC.fr 2012 :: Cascalog : progammation logique pour HadoopOSDC.fr 2012 :: Cascalog : progammation logique pour Hadoop
OSDC.fr 2012 :: Cascalog : progammation logique pour Hadoop
 
Using Scala Slick at FortyTwo
Using Scala Slick at FortyTwoUsing Scala Slick at FortyTwo
Using Scala Slick at FortyTwo
 
Indeed My Jobs: A case study in ReactJS and Redux (Meetup talk March 2016)
Indeed My Jobs: A case study in ReactJS and Redux (Meetup talk March 2016)Indeed My Jobs: A case study in ReactJS and Redux (Meetup talk March 2016)
Indeed My Jobs: A case study in ReactJS and Redux (Meetup talk March 2016)
 
How te bring common UI patterns to ADF
How te bring common UI patterns to ADFHow te bring common UI patterns to ADF
How te bring common UI patterns to ADF
 

En vedette

En vedette (6)

A Slice of Scala
A Slice of Scala A Slice of Scala
A Slice of Scala
 
Deploying the Graph
Deploying the GraphDeploying the Graph
Deploying the Graph
 
Hypermedia for the iOS developer - Swipe 2012
Hypermedia for the iOS developer - Swipe  2012Hypermedia for the iOS developer - Swipe  2012
Hypermedia for the iOS developer - Swipe 2012
 
Building Hypermedia API's - YOW! Night - March 2013
Building Hypermedia API's - YOW! Night - March 2013Building Hypermedia API's - YOW! Night - March 2013
Building Hypermedia API's - YOW! Night - March 2013
 
YOW Mobile Night 2011 - The realestate.com.au mobile story
YOW Mobile Night 2011 - The realestate.com.au mobile storyYOW Mobile Night 2011 - The realestate.com.au mobile story
YOW Mobile Night 2011 - The realestate.com.au mobile story
 
Simpler Web Architectures Now! (At The Frontend 2016)
Simpler Web Architectures Now! (At The Frontend 2016)Simpler Web Architectures Now! (At The Frontend 2016)
Simpler Web Architectures Now! (At The Frontend 2016)
 

Similaire à Swipe 2011 - iOS Gems

Learning jquery-in-30-minutes-1195942580702664-3
Learning jquery-in-30-minutes-1195942580702664-3Learning jquery-in-30-minutes-1195942580702664-3
Learning jquery-in-30-minutes-1195942580702664-3
luckysb16
 
Kick start with j query
Kick start with j queryKick start with j query
Kick start with j query
Md. Ziaul Haq
 
EclipseCon2011 Cross-Platform Mobile Development with Eclipse
EclipseCon2011 Cross-Platform Mobile Development with EclipseEclipseCon2011 Cross-Platform Mobile Development with Eclipse
EclipseCon2011 Cross-Platform Mobile Development with Eclipse
Heiko Behrens
 
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesDesarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Luis Curo Salvatierra
 
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2KZepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Thomas Fuchs
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说
Ting Lv
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
Sven Haiges
 

Similaire à Swipe 2011 - iOS Gems (20)

Learning jquery-in-30-minutes-1195942580702664-3
Learning jquery-in-30-minutes-1195942580702664-3Learning jquery-in-30-minutes-1195942580702664-3
Learning jquery-in-30-minutes-1195942580702664-3
 
Kick start with j query
Kick start with j queryKick start with j query
Kick start with j query
 
EclipseCon2011 Cross-Platform Mobile Development with Eclipse
EclipseCon2011 Cross-Platform Mobile Development with EclipseEclipseCon2011 Cross-Platform Mobile Development with Eclipse
EclipseCon2011 Cross-Platform Mobile Development with Eclipse
 
Iniciando com jquery
Iniciando com jqueryIniciando com jquery
Iniciando com jquery
 
Learning jQuery in 30 minutes
Learning jQuery in 30 minutesLearning jQuery in 30 minutes
Learning jQuery in 30 minutes
 
For mobile 5/13'
For mobile 5/13'For mobile 5/13'
For mobile 5/13'
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
 
Javascript & jQuery: A pragmatic introduction
Javascript & jQuery: A pragmatic introductionJavascript & jQuery: A pragmatic introduction
Javascript & jQuery: A pragmatic introduction
 
Swift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-CSwift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-C
 
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesDesarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móviles
 
Beyond Breakpoints: Advanced Debugging with XCode
Beyond Breakpoints: Advanced Debugging with XCodeBeyond Breakpoints: Advanced Debugging with XCode
Beyond Breakpoints: Advanced Debugging with XCode
 
Objective-C Crash Course for Web Developers
Objective-C Crash Course for Web DevelopersObjective-C Crash Course for Web Developers
Objective-C Crash Course for Web Developers
 
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2KZepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2K
 
Cubes - Lightweight Python OLAP (EuroPython 2012 talk)
Cubes - Lightweight Python OLAP (EuroPython 2012 talk)Cubes - Lightweight Python OLAP (EuroPython 2012 talk)
Cubes - Lightweight Python OLAP (EuroPython 2012 talk)
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
Developing iOS REST Applications
Developing iOS REST ApplicationsDeveloping iOS REST Applications
Developing iOS REST Applications
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
 
CREATE INDEX … USING VODKA. VODKA CONNECTING INDEXES, Олег Бартунов, Александ...
CREATE INDEX … USING VODKA. VODKA CONNECTING INDEXES, Олег Бартунов, Александ...CREATE INDEX … USING VODKA. VODKA CONNECTING INDEXES, Олег Бартунов, Александ...
CREATE INDEX … USING VODKA. VODKA CONNECTING INDEXES, Олег Бартунов, Александ...
 

Dernier

Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
UXDXConf
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Peter Udo Diehl
 

Dernier (20)

Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
 
Oauth 2.0 Introduction and Flows with MuleSoft
Oauth 2.0 Introduction and Flows with MuleSoftOauth 2.0 Introduction and Flows with MuleSoft
Oauth 2.0 Introduction and Flows with MuleSoft
 
Easier, Faster, and More Powerful – Notes Document Properties Reimagined
Easier, Faster, and More Powerful – Notes Document Properties ReimaginedEasier, Faster, and More Powerful – Notes Document Properties Reimagined
Easier, Faster, and More Powerful – Notes Document Properties Reimagined
 
Syngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdf
 
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
 
Microsoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - QuestionnaireMicrosoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - Questionnaire
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 Warsaw
 
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
 
IESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIESVE for Early Stage Design and Planning
IESVE for Early Stage Design and Planning
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024
 
Designing for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at ComcastDesigning for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at Comcast
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM Performance
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
 
TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024
 

Swipe 2011 - iOS Gems