SlideShare a Scribd company logo
iOS Development with Blocks Jeff Kelley (@jeff_r_kelley) MobiDevDay Detroit | February 19, 2011 Slides will be on blog.slaunchaman.com
Introduction Blocks What are blocks? Why should we use blocks? Grand Central Dispatch How does GCD help iOS development?
Blocks Apple extension to the C language Similar to closures, lambdas, etc. Encapsulate code like a function, but with extra “magic”
Your First Block void (^helloWorldBlock)(void) = ^ { printf ("Hello, World!\n"); };
Calling Your First Block void (^helloWorldBlock)(void) = ^ { printf ("Hello, World!\n"); }; helloWorldBlock();
Blocks That Return Blocks return just like functions. int (^fortyTwo)(void) = ^{ return 42; } int a = fortyTwo();
Blocks That Take Arguments Just like functions: BOOL (^isFortyTwo)(int) = ^(int a) { return (a == 42); } BOOL myBool = isFortyTwo(5); // NO
Blocks Capture Scope int a = 42; void (^myBlock)(void) = ^{ printf("a = %d\n", a); }; myBlock();
int a = 42; void (^myBlock)(void) = ^{ a++; printf("a = %d\n", a); }; myBlock();
__block  int a = 42; void (^myBlock)(void) = ^{ a++; printf("a = %d\n", a); }; myBlock();
Block Typedefs Simple block that returns an int and takes a float: typedef int (^floatToIntBlock)(float); Now initialize it: floatToIntBlock foo = ^(float a) {   return (int)a; };
Using Blocks as Arguments Method Signature: - (void)doThisBlock:(void (^)(id obj))block returns void, takes id argument
Block Typedefs As Arguments First typedef the block, then use it as an argument: typedef int (^floatToIntBlock)(float); void useMyBlock(floatToIntBlock foo);
Block Scope void (^myBlock)(void); if (someValue == YES) { myBlock = ^{ printf("YES!\n") }; } else { myBlock = ^ { printf("NO!\n") }; }
Block Memory Management Block_copy() and Block_release() Copied onto heap Blocks are Objective-C objects! [myBlock copy]; [myBlock release];
Block Memory Management Unlike Objective-C objects, blocks are created on the stack Block_copy() moves them to the heap Block_retain()  does not . Can also call [myBlock autorelease]
NSString *helloWorld = [[NSString alloc] initWithString:@"Hello, World!"]; void (^helloBlock)(void) = ^{ NSLog(@"%@", helloWorld); }; [helloWorld release]; helloBlock(); Blocks Retain Objects
What Are Blocks Good For? Replacing Callbacks Notification Handlers Enumeration
What Are Blocks Good For? Replacing Callbacks Notification Handlers Enumeration
Replacing Callbacks Old UIView animations: [UIView beginAnimations:@"foo" context:nil]; [UIView setAnimationDelegate:self]; [UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)]; Then you implement the callback
Replacing Callbacks - (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context { if ([animationID isEqualToString:kIDOne]) { … } else if ([animationID isEqualToString:kIDTwo]) { … } }
Replacing Callbacks New UIView Animations: [UIView animateWithDuration:0.3   animations:^{   [myView setAlpha:0.0f];   }   completion:^(BOOL finished) {   [self doSomething];   }];
Replacing Callbacks New UIView Animations: [UIView  animateWithDuration:0.3   animations:^{   [myView setAlpha:0.0f];   }   completion:^(BOOL finished) {   [self doSomething];   }];
Replacing Callbacks New UIView Animations: [UIView animateWithDuration:0.3   animations:^{   [myView setAlpha:0.0f];   }   completion:^(BOOL finished) {   [self doSomething];   }];
Replacing Callbacks New UIView Animations: [UIView animateWithDuration:0.3   animations:^{   [myView setAlpha:0.0f];   }   completion:^(BOOL finished) {   [self doSomething];   } ];
What Are Blocks Good For? Replacing Callbacks Notification Handlers Enumeration
Notification Handlers Old Notifications: [notificationCenter addObserver:self   selector:@selector(foo:)   name:kMyNotification   object:myObject];
Notification Handlers Old Notifications: Userinfo Dictionaries - (void)foo:(NSNotification *)aNotification {   NSDictionary *userInfo = [aNotification userInfo];   NSString *UID = [userInfo objectForKey:kIDKey];   NSNumber *value = [userInfo objectForKey:kValueKey]; }
Notification Handlers New Notification Handlers: [notificationCenter addObserverForName:kName   object:myObject   queue:nil   usingBlock:^(NSNotification *aNotification) {   [myObject doSomething]; }]; [myObject startLongTask];
What Are Blocks Good For? Replacing Callbacks Notification Handlers Enumeration
Enumeration Basic Enumeration for (int i = 0; i < [myArray count]; i++) { id obj = [myArray objectAtIndex:i]; [obj doSomething]; }
Enumeration But… for (int i = 0; i < [myArray count]; i++) {   id obj = [myArray objectAtIndex:i];   [obj doSomething];   for (int j = 0; j < [obj count]; j++) {   // Very interesting code here.   } }
Enumeration NSEnumerator NSArray *anArray = // ... ; NSEnumerator *enumerator = [anArray objectEnumerator]; id object; while ((object = [enumerator nextObject])) { // do something with object... }
Enumeration Fast Enumeration (10.5+) for (id obj in myArray) { [obj doSomething]; }
Enumeration Block-based enumeration [myArray enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) { [obj doSomething]; }];
Enumeration So why use block-based enumeration? -enumerateObjectsWithOptions:usingBlock: NSEnumerationReverse NSEnumerationConcurrent Concurrent processing! And for free!
What Are Blocks Good For? Replacing Callbacks Notification Handlers Enumeration
What Are Blocks Good For? Replacing Callbacks Notification Handlers Enumeration Sorting
What Are Blocks Good For? Replacing Callbacks Notification Handlers Enumeration Sorting
Sorting NSArray -sortedArrayWithOptions:usingComparator: Concurrent sorting for free!
Blocks Wrap-Up Carat Syntax  Block Memory Management Using Blocks as Arguments Replacing Callbacks, Notification Handlers, Enumeration, and Sorting
Intro to Grand Central Dispatch
Moore’s Law The quantity of transistors  that can be placed inexpensively on an  integrated circuit  has doubled approximately every two years. The trend has continued for more than half a century and is not expected to stop until 2015 or later. Wikipedia
Grand Central Dispatch (GCD) Open-source threading library (libdispatch) Apache license Automatically optimizes threading Provides queues, timers, event handlers, etc.
Simple GCD dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); dispatch_async(queue, ^{ [self  performLongTask]; }
Basic Dispatch Functions dispatch_async(queue, block); dispatch_async_f(queue, context, func); Schedules block or function on queue, returns immediately dispatch_sync(queue, block); dispatch_sync_f(queue, context, func); Schedules block or function on queue, blocks until completion
Dispatch Queues dispatch_queue_t Main Queue Analogous to main thread (Do your UI operations here) dispatch_get_main_queue()
Global Queues dispatch_get_global_queue(priority, flags); priority is one of three constants: DISPATCH_QUEUE_PRIORITY_LOW DISPATCH_QUEUE_PRIORITY_NORMAL DISPATCH_QUEUE_PRIORITY_HIGH secong arg should always be 0ul (for now)
Making Queues dispatch_queue_create(label, attr) Use reverse DNS for label com.example.myQueue pass NULL for attr Be sure to use dispatch_release()
Using Queues Custom queues are serial First-in, first-out, one at a time Global queues are concurrent GCD automatically chooses how many (usually # of CPU cores)
Ad

More Related Content

What's hot (20)

Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
OdessaJS Conf
 
Python Objects
Python ObjectsPython Objects
Python Objects
Quintagroup
 
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
OdessaJS Conf
 
Grand Central Dispatch Design Patterns
Grand Central Dispatch Design PatternsGrand Central Dispatch Design Patterns
Grand Central Dispatch Design Patterns
Robert Brown
 
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...
Stefan Marr
 
Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! 
aleks-f
 
Garbage collector in python
Garbage collector in pythonGarbage collector in python
Garbage collector in python
Ibrahim Kasim
 
Building High-Performance Language Implementations With Low Effort
Building High-Performance Language Implementations With Low EffortBuilding High-Performance Language Implementations With Low Effort
Building High-Performance Language Implementations With Low Effort
Stefan Marr
 
Ns2: Introduction - Part I
Ns2: Introduction - Part INs2: Introduction - Part I
Ns2: Introduction - Part I
Ajit Nayak
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴
명신 김
 
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Sergey Platonov
 
Ns2: OTCL - PArt II
Ns2: OTCL - PArt IINs2: OTCL - PArt II
Ns2: OTCL - PArt II
Ajit Nayak
 
Basic Packet Forwarding in NS2
Basic Packet Forwarding in NS2Basic Packet Forwarding in NS2
Basic Packet Forwarding in NS2
Teerawat Issariyakul
 
NS2 Classifiers
NS2 ClassifiersNS2 Classifiers
NS2 Classifiers
Teerawat Issariyakul
 
Return of c++
Return of c++Return of c++
Return of c++
Yongwei Wu
 
The Ring programming language version 1.3 book - Part 84 of 88
The Ring programming language version 1.3 book - Part 84 of 88The Ring programming language version 1.3 book - Part 84 of 88
The Ring programming language version 1.3 book - Part 84 of 88
Mahmoud Samir Fayed
 
Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013
aleks-f
 
Dynamic C++ Silicon Valley Code Camp 2012
Dynamic C++ Silicon Valley Code Camp 2012Dynamic C++ Silicon Valley Code Camp 2012
Dynamic C++ Silicon Valley Code Camp 2012
aleks-f
 
Engineering fast indexes (Deepdive)
Engineering fast indexes (Deepdive)Engineering fast indexes (Deepdive)
Engineering fast indexes (Deepdive)
Daniel Lemire
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6
Solution4Future
 
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
OdessaJS Conf
 
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
OdessaJS Conf
 
Grand Central Dispatch Design Patterns
Grand Central Dispatch Design PatternsGrand Central Dispatch Design Patterns
Grand Central Dispatch Design Patterns
Robert Brown
 
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...
Stefan Marr
 
Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! 
aleks-f
 
Garbage collector in python
Garbage collector in pythonGarbage collector in python
Garbage collector in python
Ibrahim Kasim
 
Building High-Performance Language Implementations With Low Effort
Building High-Performance Language Implementations With Low EffortBuilding High-Performance Language Implementations With Low Effort
Building High-Performance Language Implementations With Low Effort
Stefan Marr
 
Ns2: Introduction - Part I
Ns2: Introduction - Part INs2: Introduction - Part I
Ns2: Introduction - Part I
Ajit Nayak
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴
명신 김
 
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Sergey Platonov
 
Ns2: OTCL - PArt II
Ns2: OTCL - PArt IINs2: OTCL - PArt II
Ns2: OTCL - PArt II
Ajit Nayak
 
The Ring programming language version 1.3 book - Part 84 of 88
The Ring programming language version 1.3 book - Part 84 of 88The Ring programming language version 1.3 book - Part 84 of 88
The Ring programming language version 1.3 book - Part 84 of 88
Mahmoud Samir Fayed
 
Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013
aleks-f
 
Dynamic C++ Silicon Valley Code Camp 2012
Dynamic C++ Silicon Valley Code Camp 2012Dynamic C++ Silicon Valley Code Camp 2012
Dynamic C++ Silicon Valley Code Camp 2012
aleks-f
 
Engineering fast indexes (Deepdive)
Engineering fast indexes (Deepdive)Engineering fast indexes (Deepdive)
Engineering fast indexes (Deepdive)
Daniel Lemire
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6
Solution4Future
 

Similar to iOS Development with Blocks (20)

Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
Azul Systems, Inc.
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
MongoDB
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCD
rsebbe
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
Doug Hawkins
 
Objective C Block
Objective C BlockObjective C Block
Objective C Block
Fantageek
 
Treinamento Qt básico - aula II
Treinamento Qt básico - aula IITreinamento Qt básico - aula II
Treinamento Qt básico - aula II
Marcelo Barros de Almeida
 
Grand Central Dispatch
Grand Central DispatchGrand Central Dispatch
Grand Central Dispatch
cqtt191
 
Klee introduction
Klee  introductionKlee  introduction
Klee introduction
Georgiana T.
 
Swift - One step forward from Obj-C
Swift -  One step forward from Obj-CSwift -  One step forward from Obj-C
Swift - One step forward from Obj-C
Nissan Tsafrir
 
Боремся с NPE вместе с Kotlin, Павел Шацких СберТех
Боремся с NPE вместе с Kotlin, Павел Шацких СберТехБоремся с NPE вместе с Kotlin, Павел Шацких СберТех
Боремся с NPE вместе с Kotlin, Павел Шацких СберТех
Сбертех | SberTech
 
Playing With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.jsPlaying With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.js
Mike Hagedorn
 
Day 1
Day 1Day 1
Day 1
Pat Zearfoss
 
4Developers 2018: Evolution of C++ Class Design (Mariusz Łapiński)
4Developers 2018: Evolution of C++ Class Design (Mariusz Łapiński)4Developers 2018: Evolution of C++ Class Design (Mariusz Łapiński)
4Developers 2018: Evolution of C++ Class Design (Mariusz Łapiński)
PROIDEA
 
iOS Selectors Blocks and Delegation
iOS Selectors Blocks and DelegationiOS Selectors Blocks and Delegation
iOS Selectors Blocks and Delegation
Jussi Pohjolainen
 
Beginning direct3d gameprogrammingcpp02_20160324_jintaeks
Beginning direct3d gameprogrammingcpp02_20160324_jintaeksBeginning direct3d gameprogrammingcpp02_20160324_jintaeks
Beginning direct3d gameprogrammingcpp02_20160324_jintaeks
JinTaek Seo
 
Java Performance Tuning
Java Performance TuningJava Performance Tuning
Java Performance Tuning
Atthakorn Chanthong
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
rashmita_mishra
 
Node.js - As a networking tool
Node.js - As a networking toolNode.js - As a networking tool
Node.js - As a networking tool
Felix Geisendörfer
 
The Ring programming language version 1.2 book - Part 5 of 84
The Ring programming language version 1.2 book - Part 5 of 84The Ring programming language version 1.2 book - Part 5 of 84
The Ring programming language version 1.2 book - Part 5 of 84
Mahmoud Samir Fayed
 
ARC - Moqod mobile talks meetup
ARC - Moqod mobile talks meetupARC - Moqod mobile talks meetup
ARC - Moqod mobile talks meetup
Moqod
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
Azul Systems, Inc.
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
MongoDB
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCD
rsebbe
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
Doug Hawkins
 
Objective C Block
Objective C BlockObjective C Block
Objective C Block
Fantageek
 
Grand Central Dispatch
Grand Central DispatchGrand Central Dispatch
Grand Central Dispatch
cqtt191
 
Swift - One step forward from Obj-C
Swift -  One step forward from Obj-CSwift -  One step forward from Obj-C
Swift - One step forward from Obj-C
Nissan Tsafrir
 
Боремся с NPE вместе с Kotlin, Павел Шацких СберТех
Боремся с NPE вместе с Kotlin, Павел Шацких СберТехБоремся с NPE вместе с Kotlin, Павел Шацких СберТех
Боремся с NPE вместе с Kotlin, Павел Шацких СберТех
Сбертех | SberTech
 
Playing With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.jsPlaying With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.js
Mike Hagedorn
 
4Developers 2018: Evolution of C++ Class Design (Mariusz Łapiński)
4Developers 2018: Evolution of C++ Class Design (Mariusz Łapiński)4Developers 2018: Evolution of C++ Class Design (Mariusz Łapiński)
4Developers 2018: Evolution of C++ Class Design (Mariusz Łapiński)
PROIDEA
 
iOS Selectors Blocks and Delegation
iOS Selectors Blocks and DelegationiOS Selectors Blocks and Delegation
iOS Selectors Blocks and Delegation
Jussi Pohjolainen
 
Beginning direct3d gameprogrammingcpp02_20160324_jintaeks
Beginning direct3d gameprogrammingcpp02_20160324_jintaeksBeginning direct3d gameprogrammingcpp02_20160324_jintaeks
Beginning direct3d gameprogrammingcpp02_20160324_jintaeks
JinTaek Seo
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
rashmita_mishra
 
The Ring programming language version 1.2 book - Part 5 of 84
The Ring programming language version 1.2 book - Part 5 of 84The Ring programming language version 1.2 book - Part 5 of 84
The Ring programming language version 1.2 book - Part 5 of 84
Mahmoud Samir Fayed
 
ARC - Moqod mobile talks meetup
ARC - Moqod mobile talks meetupARC - Moqod mobile talks meetup
ARC - Moqod mobile talks meetup
Moqod
 
Ad

Recently uploaded (20)

Building the Customer Identity Community, Together.pdf
Building the Customer Identity Community, Together.pdfBuilding the Customer Identity Community, Together.pdf
Building the Customer Identity Community, Together.pdf
Cheryl Hung
 
fennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solutionfennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solution
shallal2
 
How to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabberHow to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabber
eGrabber
 
Mastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B LandscapeMastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B Landscape
marketing943205
 
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Cyntexa
 
An Overview of Salesforce Health Cloud & How is it Transforming Patient Care
An Overview of Salesforce Health Cloud & How is it Transforming Patient CareAn Overview of Salesforce Health Cloud & How is it Transforming Patient Care
An Overview of Salesforce Health Cloud & How is it Transforming Patient Care
Cyntexa
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
Cybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and MitigationCybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and Mitigation
VICTOR MAESTRE RAMIREZ
 
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz
 
AI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of DocumentsAI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of Documents
UiPathCommunity
 
Slack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teamsSlack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teams
Nacho Cougil
 
AsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API DesignAsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API Design
leonid54
 
Agentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community MeetupAgentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community Meetup
Manoj Batra (1600 + Connections)
 
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
João Esperancinha
 
AI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamsonAI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamson
UXPA Boston
 
IT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information TechnologyIT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information Technology
SHEHABALYAMANI
 
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
James Anderson
 
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
Ivano Malavolta
 
Dark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanizationDark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanization
Jakub Šimek
 
Viam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdfViam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdf
camilalamoratta
 
Building the Customer Identity Community, Together.pdf
Building the Customer Identity Community, Together.pdfBuilding the Customer Identity Community, Together.pdf
Building the Customer Identity Community, Together.pdf
Cheryl Hung
 
fennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solutionfennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solution
shallal2
 
How to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabberHow to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabber
eGrabber
 
Mastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B LandscapeMastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B Landscape
marketing943205
 
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Cyntexa
 
An Overview of Salesforce Health Cloud & How is it Transforming Patient Care
An Overview of Salesforce Health Cloud & How is it Transforming Patient CareAn Overview of Salesforce Health Cloud & How is it Transforming Patient Care
An Overview of Salesforce Health Cloud & How is it Transforming Patient Care
Cyntexa
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
Cybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and MitigationCybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and Mitigation
VICTOR MAESTRE RAMIREZ
 
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz
 
AI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of DocumentsAI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of Documents
UiPathCommunity
 
Slack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teamsSlack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teams
Nacho Cougil
 
AsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API DesignAsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API Design
leonid54
 
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
João Esperancinha
 
AI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamsonAI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamson
UXPA Boston
 
IT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information TechnologyIT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information Technology
SHEHABALYAMANI
 
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
James Anderson
 
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
Ivano Malavolta
 
Dark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanizationDark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanization
Jakub Šimek
 
Viam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdfViam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdf
camilalamoratta
 
Ad

iOS Development with Blocks

  • 1. iOS Development with Blocks Jeff Kelley (@jeff_r_kelley) MobiDevDay Detroit | February 19, 2011 Slides will be on blog.slaunchaman.com
  • 2. Introduction Blocks What are blocks? Why should we use blocks? Grand Central Dispatch How does GCD help iOS development?
  • 3. Blocks Apple extension to the C language Similar to closures, lambdas, etc. Encapsulate code like a function, but with extra “magic”
  • 4. Your First Block void (^helloWorldBlock)(void) = ^ { printf (&quot;Hello, World!\n&quot;); };
  • 5. Calling Your First Block void (^helloWorldBlock)(void) = ^ { printf (&quot;Hello, World!\n&quot;); }; helloWorldBlock();
  • 6. Blocks That Return Blocks return just like functions. int (^fortyTwo)(void) = ^{ return 42; } int a = fortyTwo();
  • 7. Blocks That Take Arguments Just like functions: BOOL (^isFortyTwo)(int) = ^(int a) { return (a == 42); } BOOL myBool = isFortyTwo(5); // NO
  • 8. Blocks Capture Scope int a = 42; void (^myBlock)(void) = ^{ printf(&quot;a = %d\n&quot;, a); }; myBlock();
  • 9. int a = 42; void (^myBlock)(void) = ^{ a++; printf(&quot;a = %d\n&quot;, a); }; myBlock();
  • 10. __block int a = 42; void (^myBlock)(void) = ^{ a++; printf(&quot;a = %d\n&quot;, a); }; myBlock();
  • 11. Block Typedefs Simple block that returns an int and takes a float: typedef int (^floatToIntBlock)(float); Now initialize it: floatToIntBlock foo = ^(float a) { return (int)a; };
  • 12. Using Blocks as Arguments Method Signature: - (void)doThisBlock:(void (^)(id obj))block returns void, takes id argument
  • 13. Block Typedefs As Arguments First typedef the block, then use it as an argument: typedef int (^floatToIntBlock)(float); void useMyBlock(floatToIntBlock foo);
  • 14. Block Scope void (^myBlock)(void); if (someValue == YES) { myBlock = ^{ printf(&quot;YES!\n&quot;) }; } else { myBlock = ^ { printf(&quot;NO!\n&quot;) }; }
  • 15. Block Memory Management Block_copy() and Block_release() Copied onto heap Blocks are Objective-C objects! [myBlock copy]; [myBlock release];
  • 16. Block Memory Management Unlike Objective-C objects, blocks are created on the stack Block_copy() moves them to the heap Block_retain() does not . Can also call [myBlock autorelease]
  • 17. NSString *helloWorld = [[NSString alloc] initWithString:@&quot;Hello, World!&quot;]; void (^helloBlock)(void) = ^{ NSLog(@&quot;%@&quot;, helloWorld); }; [helloWorld release]; helloBlock(); Blocks Retain Objects
  • 18. What Are Blocks Good For? Replacing Callbacks Notification Handlers Enumeration
  • 19. What Are Blocks Good For? Replacing Callbacks Notification Handlers Enumeration
  • 20. Replacing Callbacks Old UIView animations: [UIView beginAnimations:@&quot;foo&quot; context:nil]; [UIView setAnimationDelegate:self]; [UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)]; Then you implement the callback
  • 21. Replacing Callbacks - (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context { if ([animationID isEqualToString:kIDOne]) { … } else if ([animationID isEqualToString:kIDTwo]) { … } }
  • 22. Replacing Callbacks New UIView Animations: [UIView animateWithDuration:0.3 animations:^{ [myView setAlpha:0.0f]; } completion:^(BOOL finished) { [self doSomething]; }];
  • 23. Replacing Callbacks New UIView Animations: [UIView animateWithDuration:0.3 animations:^{ [myView setAlpha:0.0f]; } completion:^(BOOL finished) { [self doSomething]; }];
  • 24. Replacing Callbacks New UIView Animations: [UIView animateWithDuration:0.3 animations:^{ [myView setAlpha:0.0f]; } completion:^(BOOL finished) { [self doSomething]; }];
  • 25. Replacing Callbacks New UIView Animations: [UIView animateWithDuration:0.3 animations:^{ [myView setAlpha:0.0f]; } completion:^(BOOL finished) { [self doSomething]; } ];
  • 26. What Are Blocks Good For? Replacing Callbacks Notification Handlers Enumeration
  • 27. Notification Handlers Old Notifications: [notificationCenter addObserver:self selector:@selector(foo:) name:kMyNotification object:myObject];
  • 28. Notification Handlers Old Notifications: Userinfo Dictionaries - (void)foo:(NSNotification *)aNotification { NSDictionary *userInfo = [aNotification userInfo]; NSString *UID = [userInfo objectForKey:kIDKey]; NSNumber *value = [userInfo objectForKey:kValueKey]; }
  • 29. Notification Handlers New Notification Handlers: [notificationCenter addObserverForName:kName object:myObject queue:nil usingBlock:^(NSNotification *aNotification) { [myObject doSomething]; }]; [myObject startLongTask];
  • 30. What Are Blocks Good For? Replacing Callbacks Notification Handlers Enumeration
  • 31. Enumeration Basic Enumeration for (int i = 0; i < [myArray count]; i++) { id obj = [myArray objectAtIndex:i]; [obj doSomething]; }
  • 32. Enumeration But… for (int i = 0; i < [myArray count]; i++) { id obj = [myArray objectAtIndex:i]; [obj doSomething]; for (int j = 0; j < [obj count]; j++) { // Very interesting code here. } }
  • 33. Enumeration NSEnumerator NSArray *anArray = // ... ; NSEnumerator *enumerator = [anArray objectEnumerator]; id object; while ((object = [enumerator nextObject])) { // do something with object... }
  • 34. Enumeration Fast Enumeration (10.5+) for (id obj in myArray) { [obj doSomething]; }
  • 35. Enumeration Block-based enumeration [myArray enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) { [obj doSomething]; }];
  • 36. Enumeration So why use block-based enumeration? -enumerateObjectsWithOptions:usingBlock: NSEnumerationReverse NSEnumerationConcurrent Concurrent processing! And for free!
  • 37. What Are Blocks Good For? Replacing Callbacks Notification Handlers Enumeration
  • 38. What Are Blocks Good For? Replacing Callbacks Notification Handlers Enumeration Sorting
  • 39. What Are Blocks Good For? Replacing Callbacks Notification Handlers Enumeration Sorting
  • 41. Blocks Wrap-Up Carat Syntax Block Memory Management Using Blocks as Arguments Replacing Callbacks, Notification Handlers, Enumeration, and Sorting
  • 42. Intro to Grand Central Dispatch
  • 43. Moore’s Law The quantity of transistors that can be placed inexpensively on an integrated circuit has doubled approximately every two years. The trend has continued for more than half a century and is not expected to stop until 2015 or later. Wikipedia
  • 44. Grand Central Dispatch (GCD) Open-source threading library (libdispatch) Apache license Automatically optimizes threading Provides queues, timers, event handlers, etc.
  • 45. Simple GCD dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); dispatch_async(queue, ^{ [self performLongTask]; }
  • 46. Basic Dispatch Functions dispatch_async(queue, block); dispatch_async_f(queue, context, func); Schedules block or function on queue, returns immediately dispatch_sync(queue, block); dispatch_sync_f(queue, context, func); Schedules block or function on queue, blocks until completion
  • 47. Dispatch Queues dispatch_queue_t Main Queue Analogous to main thread (Do your UI operations here) dispatch_get_main_queue()
  • 48. Global Queues dispatch_get_global_queue(priority, flags); priority is one of three constants: DISPATCH_QUEUE_PRIORITY_LOW DISPATCH_QUEUE_PRIORITY_NORMAL DISPATCH_QUEUE_PRIORITY_HIGH secong arg should always be 0ul (for now)
  • 49. Making Queues dispatch_queue_create(label, attr) Use reverse DNS for label com.example.myQueue pass NULL for attr Be sure to use dispatch_release()
  • 50. Using Queues Custom queues are serial First-in, first-out, one at a time Global queues are concurrent GCD automatically chooses how many (usually # of CPU cores)

Editor's Notes

  • #2: -Straw Poll: Who here has done iOS development before? -C development?
  • #13: After: but that’s ugly. We can make this look better.
  翻译: