SlideShare a Scribd company logo
Objective-C Runtime
in Practice
CocoaheadsBE - Kontich, 2013-12-03
Introduction
Tom Adriaenssen
I love...
‣ ... my wife
‣ ... my 4 kids
‣ ... to code
‣ ... to play a game of squash
‣ ... good beer
I open sourced...
... some code:
‣ IIViewDeckController: “An
implementation of the
sliding functionality found in
the Path 2.0 or Facebook
iOS apps.”
‣ IIDateExtensions
‣ IIPopoverStatusItem
See: http://github.com/inferis
I made...
... some apps:

Butane
http://getbutane.com
Hi, @10to1!

Drash

http://dra.sh
Agenda
Agenda
‣ RUNTIME WHUT?
‣ What is an object?
‣ In practice
RUNTIME
Runtime WHUT?
‣ obj-c runtime is "always present"
‣ You can't use Objective-c without the runtime.
‣ Works behind the scenes:
‣ most developers aren't even aware it is there
and that they’r using it
‣ puts the objective in Objective-C
‣ implemented as dynamic shared library
‣ loaded by default by the OS
Runtime WHUT?
‣ Supports the most important features of
the language
‣ object oriented
‣ messaging
‣ protocols
‣ dynamic typing
‣ forwarding
Foundation
‣ is a support framework
‣ included by default
‣ The Foundation framework defines a base layer of
Objective-C classes.
‣ a set of useful primitive object classes (NSObject,
NSProxy, …)
‣ introduces several paradigms that define functionality
not covered by the Objective-C language.
‣ reflection
‣ memory management
‣ archiving
C + Runtime = Obj-C
‣ The runtime is what makes objective-c.
‣ The runtime is the implementation of the
syntactic "objective" sugar on top of c
‣ You can write any cocoa program
using pure C, but it's hard and
verbose.
Demo
A pure C Objective-C app
In practice
‣ runtime.h overview
‣ Foundation.h, the “simple” stuff
‣ runtime.h, the “spicy” stuff
runtime.h
‣ #import <objc/runtime.h>
‣ a number of C functions to interact with the runtime
‣ Several “categories” of interactions
‣ objc_... interact with toplevel runtime (eg register a class)
‣ class_... interact with classes (eg make subclass)
‣ object_... interact with objects (eg get classname)
‣ method_... interact with methods (eg get the number of arguments)
‣ ivar_... interact with ivars (eg get the type of an ivar)
‣ property_... interact with properties (eg get the name of a property)
‣ protocol_... interact with protocols (eg get properties of a protocol)
‣ sel_... interact with selectors (eg register selector names)
‣ imp_...  interact with method implementations (provide implementations
using blocks)
C? Yuk.
Foundation.h to the rescue
‣ The Foundation library provides an obj-c
interface to some of the runtime calls.
	 #include  <Foundation/Foundation.h>  	

‣ Check your .pch file: it should be there
‣ iOS: directly
‣ OSX: via #include  <Cocoa.h>.
Foundation.h to the rescue
‣ NSObject:
‣

-­‐(BOOL)isKindOfClass:(Class)class;  

‣

-­‐(Class)class;  

‣ Functions:
‣

NSString*  NSStringFromClass(Class  aClass);  

‣

Class  NSSelectorFromString(NSString*  aSelectorName);
Dealing with classes
‣ +  (Class)class;  

‣ Returns self (the class object). Since this is a
class object, it returns the class itself.
‣ +  (Class)superclass;  

‣ Returns the class object for the receiver’s
superclass. Gets the parent class of a given
class.
‣ +  (BOOL)isSubclassOfClass:(Class)aClass;  

‣ Returns a Boolean value that indicates whether
the receiving class is a subclass of, or identical
to, a given class.
Demo
Classes
Dealing with classes
‣ -­‐  (BOOL)isKindOfClass:(Class)aClass;  

‣ Returns a Boolean value that indicates whether
the receiver is an instance of given class or an
instance of any class that inherits from that class.
‣ -­‐  (BOOL)isMemberOfClass:(Class)aClass;  

‣ Returns a Boolean value that indicates whether
the receiver is an instance of a given class.
‣ These are not the same!
‣ isKindOfClass also works on subclass instances
‣ isMemberOfClass only works on exact class
instances
Demo
More classes
Protocols
‣ -­‐  (BOOL)conformsToProtocol:(Protocol  *)aProtocol;  

‣ Returns a Boolean value that indicates whether the
receiver conforms to a given protocol.
‣ A class is said to “conform to” a protocol if it
adopts the protocol or inherits from another class
that adopts it. Protocols are adopted by listing
them within angle brackets after the interface
declaration.
‣ This does not mean that the class listens to the
protocols messages explicitly!
Messages
‣ -­‐  (BOOL)respondsToSelector:(SEL)selector  

‣ Returns a Boolean value that indicates whether the receiving class
responds to a given selector.
‣ If this returns YES, you can safely send the message to the object.
‣ +  (BOOL)instancesRespondToSelector:(SEL)aSelector;  

‣ Returns a Boolean value that indicates whether instances of the receiver
are capable of responding to a given selector.
‣ When you have a Class handy and not an instance of that class. Saves
you creating an instance.
‣ Is smart enough to discover if the class actually implements the message!
‣ -­‐  (id)performSelector:(SEL)selector  

‣ Sends a specified message to the receiver and returns the result of the
message.
Demo
protocols & messages
Dynamic messaging
‣ So what actually happens when you call

[foo bar]?
‣ when foo implements bar, that bar get
executed. Instant happy.
‣ but what when there's no bar
implementation?
1. try Lazy Method Resolution
2. try Fast forwarding
3. try Normal forwarding
4. *kaboom*
Dynamic messaging
1. Lazy method resolution

the runtime sends +resolveInstanceMethod:
(or +resolveClassMethod: for class methods)
to the class in question.
‣ If that method returns YES, the message
send is restarted under the assumption
that the appropriate method has now been
added.
2. Fast forwarding
3. Normal forwarding
4. *kaboom*
Dynamic messaging
1. Lazy method resolution
2. Fast forwarding

The instance receiving the message is sent forwardingTargetForSelector:, but only if it implements it.
‣ If it implements this method and it returns something
other than nil or self, the whole message sending process
is restarted with that return value as the new target.
‣ forwards the message to another object
‣ no method implementation is added
‣ target object can use whatever method implementation
as it sees fit.
3. Normal forwarding
4. *kaboom*
Dynamic messaging
1. Lazy method resolution
2. Fast forwarding
3. Normal forwarding

Two step process:
1. First the runtime will send 

-instanceMethodSignatureForSelector: to see what kind
of argument and return types are present.
2. If a valid method signature is returned, the runtime
creates an NSInvocation describing the message being
sent
3. finally -forwardInvocation: is sent to the instance. The
instance should then use the NSInvocation on a target
object to execute the method.
4. *kaboom*
Dynamic messaging
1. Lazy method resolution
2. Fast forwarding
3. Normal forwarding
4. *kaboom*

The runtime calls -doesNotRecognizeSelector:
on the instance.
‣ Default behavior is to throw an
NSInvalidArgumentException, but you could
override this if you’d want to
‣ but! be careful -> errors will go
undetected!
Lazy method resolution
‣ Resolves/creates a method at runtime. Allows a
class to create a method when it doesn't exist.
‣ Override one (or both) of these:
‣ +  (BOOL)resolveClassMethod:(SEL)sel;    

‣ Dynamically provides an implementation for a
given selector for a class method.
‣ +  (BOOL)resolveInstanceMethod:(SEL)sel;  

‣ Dynamically provides an implementation for a
given selector for an instance method.
Lazy method resolution
‣ So how does this work?
‣ implement +resolveInstanceMethod:
‣ check the selector
‣ provide an implementation
‣ class_addMethod()
‣ need a method IMP:
‣ copy an existing method
‣ use a function
‣ make new method using a block

!
‣ Same applies to +resolveClassMethod:
‣ resolve happens the first time a method is not found (and only then if you return YES from the
resolver method)
‣ if you don't add an implementation but return YES anyway the you'll get an
NSInvalidArgumentException.
Demo
lazy method resolution
Fast forwarding
‣ You can provide an interface but have the actual
implementation be in another object.
‣ forward messages from one object to another
‣ for the user, it is as if the first object handles the call
‣ the actual handling object is "hidden" from the user
!

‣ So how does this work?
‣ implement -forwardingTargetForSelector:
‣ check the selector
‣ provide an object that can handle the selector
Demo
fast forwarding
Normal forwarding
‣ have the object provide a method signature for the selector, so
the runtime knows what arguments and return type there should
be.
‣ then forward an NSInvocation on an object you choose.
‣ basically the same as fast forwarding but more low level and a
bit more verbose
‣ So how does this work?
‣ implement +instanceMethodSignatureForSelector:
‣ check the selector
‣ provide an NSMethodSignature* that describes the selector
‣ implement forwardInvocation:
Demo
normal forwarding
Swizzling
‣ Swizzling is exchanging the implementation of
one factor of the runtime with another factor.
In Objective-C, you can apply this on two
levels: method swizzling and class swizzling.
‣ Method swizzling
‣ Class swizzling
‣ Dynamic class generation
Method swizzling
‣ You need to have two methods with an
implementation
‣ Can exchange the implementation of the
methods with each other
‣ Not only in your own code, but you can
modify framework code too! (eg UIView, …)
Demo
method swizzling
Class swizzling
‣ No real swizzling…
‣ Just change the class on an existing object
‣ best used with subclasses or classes with
the same layout/interface
‣ memory allocation is not changed when
changing classes
‣ otherwise: NUKULAR EXCEPTION
Demo
class swizzling
Dynamic class generation
‣ Generate a class at runtime
‣ Provide methods and implementations as
you see fit
‣ add new functionality
‣ change existing functionality
Demo
dynamic class generation
For closing…	
‣ Generated properties
‣ provide property storage in your own
backing (eg plist)
‣ No implementations in code
‣ generate them at runtime
‣ only provide methods in interface
‣ no compiler warnings
Demo
property generation
Warning-fixing
‣ When providing dynamic implementations of selectors, the compiler will emit
warnings for the “unimplemented” messages.
‣ Fix these by placing them in a category instead of in the @interface declaration
@interface  AwesomeClass  
@end  

!
!
@interface  AwesomeClass  (Dynamic)  
!
!
//  look  ma,  no  warning  
!
-­‐  (void)withoutCodeButDynamicallyGenerated;  
!
@end
!
‣ For properties
‣ declare a property as you normally would using @property syntax in your
@interface
‣ specify @dynamic <propertyName> in you @implementation to make sure
the compiler doesn’t autosynthesize the property
‣ or use the same technique as above
Opensourced examples

‣ You can find the example projects use to
demo each aspect in my Github account:
‣ https://github.com/Inferis/Objective-CRuntime
Useful References
‣ Apple’s runtime documentation:
‣ runtime reference: https://developer.apple.com/library/mac/
documentation/cocoa/reference/objcruntimeref/Reference/
reference.html
‣ programming guide: https://developer.apple.com/library/mac/
documentation/cocoa/conceptual/objcruntimeguide/
objcruntimeguide.pdf
‣ Mike Ash’s blog: http://www.mikeash.com/pyblog
‣ objective-c: http://www.mikeash.com/pyblog/?tag=objectiveC
‣ friday Q&A: http://www.mikeash.com/pyblog/?tag=fridayqna
‣ Jon Rentzsch swizzling helpers:
‣ https://github.com/rentzsch/jrswizzle
Thanks for listening.
Questions? Contact me:
Twitter: @inferis
App.Net: @inferis
E-mail: tom@interfaceimplementation.be
vCard: http://inferis.org

More Related Content

What's hot

Invokedynamic / JSR-292
Invokedynamic / JSR-292Invokedynamic / JSR-292
Invokedynamic / JSR-292ytoshima
 
Getting started with typescript
Getting started with typescriptGetting started with typescript
Getting started with typescript
C...L, NESPRESSO, WAFAASSURANCE, SOFRECOM ORANGE
 
Java vs. C/C++
Java vs. C/C++Java vs. C/C++
Java vs. C/C++
Azul Systems Inc.
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
Mats Bryntse
 
Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Anton Arhipov
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
Mindfire Solutions
 
TypeScript
TypeScriptTypeScript
TypeScript
Oswald Campesato
 
Native code in Android applications
Native code in Android applicationsNative code in Android applications
Native code in Android applicationsDmitry Matyukhin
 
Objective-c for Java Developers
Objective-c for Java DevelopersObjective-c for Java Developers
Objective-c for Java DevelopersMuhammad Abdullah
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
Dmitry Sheiko
 
Building a java tracer
Building a java tracerBuilding a java tracer
Building a java tracerrahulrevo
 
Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012Anton Arhipov
 
Bytecode manipulation with Javassist and ASM
Bytecode manipulation with Javassist and ASMBytecode manipulation with Javassist and ASM
Bytecode manipulation with Javassist and ASM
ashleypuls
 
Js fwdays unit tesing javascript(by Anna Khabibullina)
Js fwdays unit tesing javascript(by Anna Khabibullina)Js fwdays unit tesing javascript(by Anna Khabibullina)
Js fwdays unit tesing javascript(by Anna Khabibullina)
Anna Khabibullina
 
JS Frameworks Day April,26 of 2014
JS Frameworks Day April,26 of 2014JS Frameworks Day April,26 of 2014
JS Frameworks Day April,26 of 2014
DA-14
 
Complete Java Course
Complete Java CourseComplete Java Course
Complete Java Course
Lhouceine OUHAMZA
 
Java script Techniques Part I
Java script Techniques Part IJava script Techniques Part I
Java script Techniques Part I
Luis Atencio
 
JS Event Loop
JS Event LoopJS Event Loop
JS Event Loop
Saai Vignesh P
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference Counting
Robert Brown
 
Kotlin
KotlinKotlin

What's hot (20)

Invokedynamic / JSR-292
Invokedynamic / JSR-292Invokedynamic / JSR-292
Invokedynamic / JSR-292
 
Getting started with typescript
Getting started with typescriptGetting started with typescript
Getting started with typescript
 
Java vs. C/C++
Java vs. C/C++Java vs. C/C++
Java vs. C/C++
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
 
TypeScript
TypeScriptTypeScript
TypeScript
 
Native code in Android applications
Native code in Android applicationsNative code in Android applications
Native code in Android applications
 
Objective-c for Java Developers
Objective-c for Java DevelopersObjective-c for Java Developers
Objective-c for Java Developers
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Building a java tracer
Building a java tracerBuilding a java tracer
Building a java tracer
 
Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012
 
Bytecode manipulation with Javassist and ASM
Bytecode manipulation with Javassist and ASMBytecode manipulation with Javassist and ASM
Bytecode manipulation with Javassist and ASM
 
Js fwdays unit tesing javascript(by Anna Khabibullina)
Js fwdays unit tesing javascript(by Anna Khabibullina)Js fwdays unit tesing javascript(by Anna Khabibullina)
Js fwdays unit tesing javascript(by Anna Khabibullina)
 
JS Frameworks Day April,26 of 2014
JS Frameworks Day April,26 of 2014JS Frameworks Day April,26 of 2014
JS Frameworks Day April,26 of 2014
 
Complete Java Course
Complete Java CourseComplete Java Course
Complete Java Course
 
Java script Techniques Part I
Java script Techniques Part IJava script Techniques Part I
Java script Techniques Part I
 
JS Event Loop
JS Event LoopJS Event Loop
JS Event Loop
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference Counting
 
Kotlin
KotlinKotlin
Kotlin
 

Similar to Objective c runtime

Scripting as a Second Language
Scripting as a Second LanguageScripting as a Second Language
Scripting as a Second Language
Rob Dunn
 
JavaScript
JavaScriptJavaScript
JavaScript
Ivano Malavolta
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
Ivano Malavolta
 
React native
React nativeReact native
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
Jeff Durta
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
Eugene Lazutkin
 
Pharo, an innovative and open-source Smalltalk
Pharo, an innovative and open-source SmalltalkPharo, an innovative and open-source Smalltalk
Pharo, an innovative and open-source SmalltalkSerge Stinckwich
 
Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?
PVS-Studio
 
Thinking In Swift
Thinking In SwiftThinking In Swift
Thinking In Swift
Janie Clayton
 
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
 
1669958779195.pdf
1669958779195.pdf1669958779195.pdf
1669958779195.pdf
venud11
 
RxJava@Android
RxJava@AndroidRxJava@Android
RxJava@Android
Maxim Volgin
 
Java Basics
Java BasicsJava Basics
Java Basics
shivamgarg_nitj
 
Checking Clang 11 with PVS-Studio
Checking Clang 11 with PVS-StudioChecking Clang 11 with PVS-Studio
Checking Clang 11 with PVS-Studio
Andrey Karpov
 
Robots in Swift
Robots in SwiftRobots in Swift
Robots in Swift
Janie Clayton
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
Abhijeet Dubey
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
Naresh Jain
 
Code quality par Simone Civetta
Code quality par Simone CivettaCode quality par Simone Civetta
Code quality par Simone Civetta
CocoaHeads France
 
My programming final proj. (1)
My programming final proj. (1)My programming final proj. (1)
My programming final proj. (1)aeden_brines
 
Artdm170 Week5 Intro To Flash
Artdm170 Week5 Intro To FlashArtdm170 Week5 Intro To Flash
Artdm170 Week5 Intro To FlashGilbert Guerrero
 

Similar to Objective c runtime (20)

Scripting as a Second Language
Scripting as a Second LanguageScripting as a Second Language
Scripting as a Second Language
 
JavaScript
JavaScriptJavaScript
JavaScript
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
 
React native
React nativeReact native
React native
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
 
Pharo, an innovative and open-source Smalltalk
Pharo, an innovative and open-source SmalltalkPharo, an innovative and open-source Smalltalk
Pharo, an innovative and open-source Smalltalk
 
Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?
 
Thinking In Swift
Thinking In SwiftThinking In Swift
Thinking In Swift
 
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
 
1669958779195.pdf
1669958779195.pdf1669958779195.pdf
1669958779195.pdf
 
RxJava@Android
RxJava@AndroidRxJava@Android
RxJava@Android
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Checking Clang 11 with PVS-Studio
Checking Clang 11 with PVS-StudioChecking Clang 11 with PVS-Studio
Checking Clang 11 with PVS-Studio
 
Robots in Swift
Robots in SwiftRobots in Swift
Robots in Swift
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
Code quality par Simone Civetta
Code quality par Simone CivettaCode quality par Simone Civetta
Code quality par Simone Civetta
 
My programming final proj. (1)
My programming final proj. (1)My programming final proj. (1)
My programming final proj. (1)
 
Artdm170 Week5 Intro To Flash
Artdm170 Week5 Intro To FlashArtdm170 Week5 Intro To Flash
Artdm170 Week5 Intro To Flash
 

More from Inferis

Practical auto layout
Practical auto layoutPractical auto layout
Practical auto layout
Inferis
 
Communicating with GIFs
Communicating with GIFsCommunicating with GIFs
Communicating with GIFs
Inferis
 
Autolayout primer
Autolayout primerAutolayout primer
Autolayout primer
Inferis
 
Adventures in Multithreaded Core Data
Adventures in Multithreaded Core DataAdventures in Multithreaded Core Data
Adventures in Multithreaded Core DataInferis
 
I Am A Switcher
I Am A SwitcherI Am A Switcher
I Am A Switcher
Inferis
 
Dynamic Silverlight
Dynamic SilverlightDynamic Silverlight
Dynamic Silverlight
Inferis
 

More from Inferis (6)

Practical auto layout
Practical auto layoutPractical auto layout
Practical auto layout
 
Communicating with GIFs
Communicating with GIFsCommunicating with GIFs
Communicating with GIFs
 
Autolayout primer
Autolayout primerAutolayout primer
Autolayout primer
 
Adventures in Multithreaded Core Data
Adventures in Multithreaded Core DataAdventures in Multithreaded Core Data
Adventures in Multithreaded Core Data
 
I Am A Switcher
I Am A SwitcherI Am A Switcher
I Am A Switcher
 
Dynamic Silverlight
Dynamic SilverlightDynamic Silverlight
Dynamic Silverlight
 

Recently uploaded

Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
UiPathCommunity
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 

Recently uploaded (20)

Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 

Objective c runtime

  • 4. I love... ‣ ... my wife ‣ ... my 4 kids ‣ ... to code ‣ ... to play a game of squash ‣ ... good beer
  • 5. I open sourced... ... some code: ‣ IIViewDeckController: “An implementation of the sliding functionality found in the Path 2.0 or Facebook iOS apps.” ‣ IIDateExtensions ‣ IIPopoverStatusItem See: http://github.com/inferis
  • 6. I made... ... some apps: Butane http://getbutane.com Hi, @10to1! Drash http://dra.sh
  • 8. Agenda ‣ RUNTIME WHUT? ‣ What is an object? ‣ In practice
  • 10. Runtime WHUT? ‣ obj-c runtime is "always present" ‣ You can't use Objective-c without the runtime. ‣ Works behind the scenes: ‣ most developers aren't even aware it is there and that they’r using it ‣ puts the objective in Objective-C ‣ implemented as dynamic shared library ‣ loaded by default by the OS
  • 11. Runtime WHUT? ‣ Supports the most important features of the language ‣ object oriented ‣ messaging ‣ protocols ‣ dynamic typing ‣ forwarding
  • 12. Foundation ‣ is a support framework ‣ included by default ‣ The Foundation framework defines a base layer of Objective-C classes. ‣ a set of useful primitive object classes (NSObject, NSProxy, …) ‣ introduces several paradigms that define functionality not covered by the Objective-C language. ‣ reflection ‣ memory management ‣ archiving
  • 13. C + Runtime = Obj-C ‣ The runtime is what makes objective-c. ‣ The runtime is the implementation of the syntactic "objective" sugar on top of c ‣ You can write any cocoa program using pure C, but it's hard and verbose.
  • 14. Demo A pure C Objective-C app
  • 15. In practice ‣ runtime.h overview ‣ Foundation.h, the “simple” stuff ‣ runtime.h, the “spicy” stuff
  • 16. runtime.h ‣ #import <objc/runtime.h> ‣ a number of C functions to interact with the runtime ‣ Several “categories” of interactions ‣ objc_... interact with toplevel runtime (eg register a class) ‣ class_... interact with classes (eg make subclass) ‣ object_... interact with objects (eg get classname) ‣ method_... interact with methods (eg get the number of arguments) ‣ ivar_... interact with ivars (eg get the type of an ivar) ‣ property_... interact with properties (eg get the name of a property) ‣ protocol_... interact with protocols (eg get properties of a protocol) ‣ sel_... interact with selectors (eg register selector names) ‣ imp_...  interact with method implementations (provide implementations using blocks)
  • 18. Foundation.h to the rescue ‣ The Foundation library provides an obj-c interface to some of the runtime calls. #include  <Foundation/Foundation.h>   ‣ Check your .pch file: it should be there ‣ iOS: directly ‣ OSX: via #include  <Cocoa.h>.
  • 19. Foundation.h to the rescue ‣ NSObject: ‣ -­‐(BOOL)isKindOfClass:(Class)class;   ‣ -­‐(Class)class;   ‣ Functions: ‣ NSString*  NSStringFromClass(Class  aClass);   ‣ Class  NSSelectorFromString(NSString*  aSelectorName);
  • 20. Dealing with classes ‣ +  (Class)class;   ‣ Returns self (the class object). Since this is a class object, it returns the class itself. ‣ +  (Class)superclass;   ‣ Returns the class object for the receiver’s superclass. Gets the parent class of a given class. ‣ +  (BOOL)isSubclassOfClass:(Class)aClass;   ‣ Returns a Boolean value that indicates whether the receiving class is a subclass of, or identical to, a given class.
  • 22. Dealing with classes ‣ -­‐  (BOOL)isKindOfClass:(Class)aClass;   ‣ Returns a Boolean value that indicates whether the receiver is an instance of given class or an instance of any class that inherits from that class. ‣ -­‐  (BOOL)isMemberOfClass:(Class)aClass;   ‣ Returns a Boolean value that indicates whether the receiver is an instance of a given class. ‣ These are not the same! ‣ isKindOfClass also works on subclass instances ‣ isMemberOfClass only works on exact class instances
  • 24. Protocols ‣ -­‐  (BOOL)conformsToProtocol:(Protocol  *)aProtocol;   ‣ Returns a Boolean value that indicates whether the receiver conforms to a given protocol. ‣ A class is said to “conform to” a protocol if it adopts the protocol or inherits from another class that adopts it. Protocols are adopted by listing them within angle brackets after the interface declaration. ‣ This does not mean that the class listens to the protocols messages explicitly!
  • 25. Messages ‣ -­‐  (BOOL)respondsToSelector:(SEL)selector   ‣ Returns a Boolean value that indicates whether the receiving class responds to a given selector. ‣ If this returns YES, you can safely send the message to the object. ‣ +  (BOOL)instancesRespondToSelector:(SEL)aSelector;   ‣ Returns a Boolean value that indicates whether instances of the receiver are capable of responding to a given selector. ‣ When you have a Class handy and not an instance of that class. Saves you creating an instance. ‣ Is smart enough to discover if the class actually implements the message! ‣ -­‐  (id)performSelector:(SEL)selector   ‣ Sends a specified message to the receiver and returns the result of the message.
  • 27. Dynamic messaging ‣ So what actually happens when you call
 [foo bar]? ‣ when foo implements bar, that bar get executed. Instant happy. ‣ but what when there's no bar implementation? 1. try Lazy Method Resolution 2. try Fast forwarding 3. try Normal forwarding 4. *kaboom*
  • 28. Dynamic messaging 1. Lazy method resolution
 the runtime sends +resolveInstanceMethod: (or +resolveClassMethod: for class methods) to the class in question. ‣ If that method returns YES, the message send is restarted under the assumption that the appropriate method has now been added. 2. Fast forwarding 3. Normal forwarding 4. *kaboom*
  • 29. Dynamic messaging 1. Lazy method resolution 2. Fast forwarding
 The instance receiving the message is sent forwardingTargetForSelector:, but only if it implements it. ‣ If it implements this method and it returns something other than nil or self, the whole message sending process is restarted with that return value as the new target. ‣ forwards the message to another object ‣ no method implementation is added ‣ target object can use whatever method implementation as it sees fit. 3. Normal forwarding 4. *kaboom*
  • 30. Dynamic messaging 1. Lazy method resolution 2. Fast forwarding 3. Normal forwarding
 Two step process: 1. First the runtime will send 
 -instanceMethodSignatureForSelector: to see what kind of argument and return types are present. 2. If a valid method signature is returned, the runtime creates an NSInvocation describing the message being sent 3. finally -forwardInvocation: is sent to the instance. The instance should then use the NSInvocation on a target object to execute the method. 4. *kaboom*
  • 31. Dynamic messaging 1. Lazy method resolution 2. Fast forwarding 3. Normal forwarding 4. *kaboom*
 The runtime calls -doesNotRecognizeSelector: on the instance. ‣ Default behavior is to throw an NSInvalidArgumentException, but you could override this if you’d want to ‣ but! be careful -> errors will go undetected!
  • 32. Lazy method resolution ‣ Resolves/creates a method at runtime. Allows a class to create a method when it doesn't exist. ‣ Override one (or both) of these: ‣ +  (BOOL)resolveClassMethod:(SEL)sel;     ‣ Dynamically provides an implementation for a given selector for a class method. ‣ +  (BOOL)resolveInstanceMethod:(SEL)sel;   ‣ Dynamically provides an implementation for a given selector for an instance method.
  • 33. Lazy method resolution ‣ So how does this work? ‣ implement +resolveInstanceMethod: ‣ check the selector ‣ provide an implementation ‣ class_addMethod() ‣ need a method IMP: ‣ copy an existing method ‣ use a function ‣ make new method using a block ! ‣ Same applies to +resolveClassMethod: ‣ resolve happens the first time a method is not found (and only then if you return YES from the resolver method) ‣ if you don't add an implementation but return YES anyway the you'll get an NSInvalidArgumentException.
  • 35. Fast forwarding ‣ You can provide an interface but have the actual implementation be in another object. ‣ forward messages from one object to another ‣ for the user, it is as if the first object handles the call ‣ the actual handling object is "hidden" from the user ! ‣ So how does this work? ‣ implement -forwardingTargetForSelector: ‣ check the selector ‣ provide an object that can handle the selector
  • 37. Normal forwarding ‣ have the object provide a method signature for the selector, so the runtime knows what arguments and return type there should be. ‣ then forward an NSInvocation on an object you choose. ‣ basically the same as fast forwarding but more low level and a bit more verbose ‣ So how does this work? ‣ implement +instanceMethodSignatureForSelector: ‣ check the selector ‣ provide an NSMethodSignature* that describes the selector ‣ implement forwardInvocation:
  • 39. Swizzling ‣ Swizzling is exchanging the implementation of one factor of the runtime with another factor. In Objective-C, you can apply this on two levels: method swizzling and class swizzling. ‣ Method swizzling ‣ Class swizzling ‣ Dynamic class generation
  • 40. Method swizzling ‣ You need to have two methods with an implementation ‣ Can exchange the implementation of the methods with each other ‣ Not only in your own code, but you can modify framework code too! (eg UIView, …)
  • 42. Class swizzling ‣ No real swizzling… ‣ Just change the class on an existing object ‣ best used with subclasses or classes with the same layout/interface ‣ memory allocation is not changed when changing classes ‣ otherwise: NUKULAR EXCEPTION
  • 44. Dynamic class generation ‣ Generate a class at runtime ‣ Provide methods and implementations as you see fit ‣ add new functionality ‣ change existing functionality
  • 46. For closing… ‣ Generated properties ‣ provide property storage in your own backing (eg plist) ‣ No implementations in code ‣ generate them at runtime ‣ only provide methods in interface ‣ no compiler warnings
  • 48. Warning-fixing ‣ When providing dynamic implementations of selectors, the compiler will emit warnings for the “unimplemented” messages. ‣ Fix these by placing them in a category instead of in the @interface declaration @interface  AwesomeClass   @end   ! ! @interface  AwesomeClass  (Dynamic)   ! ! //  look  ma,  no  warning   ! -­‐  (void)withoutCodeButDynamicallyGenerated;   ! @end ! ‣ For properties ‣ declare a property as you normally would using @property syntax in your @interface ‣ specify @dynamic <propertyName> in you @implementation to make sure the compiler doesn’t autosynthesize the property ‣ or use the same technique as above
  • 49. Opensourced examples ‣ You can find the example projects use to demo each aspect in my Github account: ‣ https://github.com/Inferis/Objective-CRuntime
  • 50. Useful References ‣ Apple’s runtime documentation: ‣ runtime reference: https://developer.apple.com/library/mac/ documentation/cocoa/reference/objcruntimeref/Reference/ reference.html ‣ programming guide: https://developer.apple.com/library/mac/ documentation/cocoa/conceptual/objcruntimeguide/ objcruntimeguide.pdf ‣ Mike Ash’s blog: http://www.mikeash.com/pyblog ‣ objective-c: http://www.mikeash.com/pyblog/?tag=objectiveC ‣ friday Q&A: http://www.mikeash.com/pyblog/?tag=fridayqna ‣ Jon Rentzsch swizzling helpers: ‣ https://github.com/rentzsch/jrswizzle
  • 51. Thanks for listening. Questions? Contact me: Twitter: @inferis App.Net: @inferis E-mail: tom@interfaceimplementation.be vCard: http://inferis.org