SlideShare a Scribd company logo
Objective C Runtime
Khoa Pham
2359Media
Today
● self = [super init]
● objc_msgSend
● ObjC Runtime
● How to use the Runtime API
● Use cases
self = [super init]
ETPAnimal *cat = [ETPAnimal cat];
NSInteger recordCount = [ETPCoreDataManager
recordCount];
self = [super init]
@interface ETPCat : ETPAnimal
@end
ETPCat *cat = [[ETPCat alloc] init]
self = [super init]
- (id)init
{
self = [super init];
if (self) {
// ETPCat does it own initialization here
}
return self;
}
self = [super init]
[super init] calls the superclass implementation of init with
the (hidden) self argument.
It can do one of these things
+ set some properties on self, and return self
+ return a different object (factory, singleton)
+ return nil
self = [super init]
ETPCat *cat = [ETPCat alloc] // 0x1111111a
[cat init] // 0x1111111b
[cat meomeo] // 0x1111111a
self = [super init]
Demo
objc_msgSend
ETPCat *cat = [[ETPCat alloc] init]
[cat setName:@”meo”]
objc_msgSend(cat, @selector(setName:), @”meo”)
objc_msgSend
Demo
objc_msgSend
@selector
SEL selector1 = @selector(initWithName:)
SEL selector2 = @selector(initWithFriends1Name::)
typedef struct objc_selector *SEL
Read more at Objective C Runtime Reference -> Data
Structure -> Class definition Data structure -> SEL
@selector
Demo
Objective C Runtime
The Objective-C Runtime is a Runtime Library, it's a library
written mainly in C & Assembler that adds the Object
Oriented capabilities to C to create Objective-C.
Objective C Runtime
Source code http://www.opensource.apple.
com/source/objc4/objc4-532/runtime/objc-class.mm
There are two versions of the Objective-C runtime—
“modern” and “legacy”. The modern version was introduced
with Objective-C 2.0 and includes a number of new
features.
Objective C Runtime
Dynamic feature
Object oriented capability
Objective C Runtime
Features
● Class elements (categories, methods, variables,
property, …)
● Object
● Messaging
● Object introspection
Objective C Runtime
@interface ETPAnimal : NSObject
@end
typedef struct objc_class *Class;
Objective C Runtime (old)
struct objc_class {
Class isa;
Class super_class OBJC2_UNAVAILABLE;
const char *name OBJC2_UNAVAILABLE;
long version OBJC2_UNAVAILABLE;
long info OBJC2_UNAVAILABLE;
long instance_size OBJC2_UNAVAILABLE;
struct objc_ivar_list *ivars OBJC2_UNAVAILABLE;
struct objc_method_list **methodLists OBJC2_UNAVAILABLE;
struct objc_cache *cache OBJC2_UNAVAILABLE;
struct objc_protocol_list *protocols OBJC2_UNAVAILABLE;
}
Objective C Runtime
typedef struct class_ro_t
{
const char * name;
const ivar_list_t * ivars;
} class_ro_t
typedef struct class_rw_t
{
const class_ro_t *ro;
method_list_t **methods;
struct class_t *firstSubclass;
struct class_t *nextSiblingClass;
} class_rw_t;
Objective C Runtime
ETPAnimal *animal = [[ETPAnimal alloc] init]
struct objc_object
{
Class isa;
// variables
};
Objective C Runtime
id someAnimal = [[ETPAnimal alloc] init]
typedef struct objc_object
{
Class isa;
} *id;
Objective C Runtime
Class is also an object, its isa pointer points to its meta
class
The metaclass is the description of the class object
Objective C Runtime
Objective-C Runtime overview
Objective C Runtime
Demo
Objective C Runtime
● Dynamic typing
● Dynamic binding
● Dynamic method resolution
● Introspection
Objective C Runtime
Dynamic typing
Dynamic typing enables the runtime to determine the type
of an object at runtime
id cat = [[ETPCat alloc] init]
- (void)acceptAnything:(id)anything;
Objective C Runtime
Dynamic binding
Dynamic binding is the process of mapping a message to a
method at runtime, rather than at compile time
Objective C Runtime
Dynamic method resolution
Provide the implementation of a method dynamically.
@dynamic
Objective C Runtime
Introspection
isKindOfClass
respondsToSelector
conformsToProtocol
How to use the Runtime API
Objective-C programs interact with the runtime system to
implement the dynamic features of the language.
● Objective-C source code
● Foundation Framework NSObject methods
● Runtime library API
Use cases
Method swizzle (IIViewDeckController)
JSON Model (Torin ‘s BaseModel)
Message forwarding
Meta programming
Use cases
Method swizzle
Use cases
Method swizzle (IIViewDeckController)
SEL presentVC = @selector(presentViewController:animated:completion:);
SEL vdcPresentVC = @selector(vdc_presentViewController:animated:completion:);
method_exchangeImplementations(class_getInstanceMethod(self, presentVC),
class_getInstanceMethod(self, vdcPresentVC));
Use cases
Method swizzle (IIViewDeckController)
- (void)vdc_presentViewController:(UIViewController *)viewControllerToPresent animated:(BOOL)
animated completion:(void (^)(void))completion {
UIViewController* controller = self.viewDeckController ?: self;
[controller vdc_presentViewController:viewControllerToPresent animated:animated completion:
completion]; // when we get here, the vdc_ method is actually the old, real method
}
Use cases
JSON Model (Torin ‘s BaseModel)
updateWithDictionary
class_copyIvarList
ivar_getName
Use cases
JSON Model (Torin ‘s BaseModel)
@interface ETPItem : BaseModel
@property (nonatomic, copy) NSString * ID;
@property (nonatomic, copy) NSString *name;
@end
ETPItem *item = [[ETPItem alloc] init];
[item updateWithDictionary:@{@”ID”: @”1”, @”name”: @”item1”}];
Message forwarding
Use cases
Meta programming
● Dynamic method naming
● Validation
● Template
● Mocking
Reference
1. http://cocoasamurai.blogspot.com/2010/01/understanding-objective-c-runtime.html
2. http://www.slideshare.net/mudphone/what-makes-objective-c-dynamic
3. http://www.cocoawithlove.com/2009/04/what-does-it-mean-when-you-assign-super.html
4. http://nshipster.com/method-swizzling/
5. http://stackoverflow.com/questions/415452/object-orientation-in-c
6. http://stackoverflow.com/questions/2766233/what-is-the-c-runtime-library
7. http://gcc.gnu.org/onlinedocs/gcc/Modern-GNU-Objective-C-runtime-API.html
8. http://www.opensource.apple.com/source/objc4/objc4-532/runtime/objc-class.mm
9. http://www.friday.com/bbum/2009/12/18/objc_msgsend-part-1-the-road-map/
10. https://www.mikeash.com/pyblog/friday-qa-2010-01-29-method-replacement-for-fun-and-profit.html
11. Pro Objective C, chapter 7, 8, 9
12. Effective Objective C, chapter 2
13. http://wiki.gnustep.org/index.php/ObjC2_FAQ
Thank you
Q&A

More Related Content

What's hot (20)

PDF
GPU Programming on CPU - Using C++AMP
Miller Lee
 
PDF
QThreads: Are You Using Them Wrong?
ICS
 
PPTX
Progress_190412
Hyo jeong Lee
 
PDF
Vulkan 1.1 Reference Guide
The Khronos Group Inc.
 
PDF
Qt multi threads
Ynon Perek
 
KEY
Runtime
Jorge Ortiz
 
PPTX
Java 14 features
Aditi Anand
 
PDF
Qt for beginners
Sergio Shevchenko
 
PDF
Native code in Android applications
Dmitry Matyukhin
 
PDF
C++ amp on linux
Miller Lee
 
PDF
OpenGL SC 2.0 Quick Reference
The Khronos Group Inc.
 
PDF
Complete Java Course
Lhouceine OUHAMZA
 
PDF
Twins: OOP and FP
RichardWarburton
 
PDF
A Brief Introduction to the Qt Application Framework
Zachary Blair
 
PDF
DLL Design with Building Blocks
Max Kleiner
 
PPTX
OpenGL Fixed Function to Shaders - Porting a fixed function application to “m...
ICS
 
PPT
Android JNI
Siva Ramakrishna kv
 
ODP
Qt Workshop
Johan Thelin
 
PPTX
Untitled presentation(4)
chan20kaur
 
PDF
What Makes Objective C Dynamic?
Kyle Oba
 
GPU Programming on CPU - Using C++AMP
Miller Lee
 
QThreads: Are You Using Them Wrong?
ICS
 
Progress_190412
Hyo jeong Lee
 
Vulkan 1.1 Reference Guide
The Khronos Group Inc.
 
Qt multi threads
Ynon Perek
 
Runtime
Jorge Ortiz
 
Java 14 features
Aditi Anand
 
Qt for beginners
Sergio Shevchenko
 
Native code in Android applications
Dmitry Matyukhin
 
C++ amp on linux
Miller Lee
 
OpenGL SC 2.0 Quick Reference
The Khronos Group Inc.
 
Complete Java Course
Lhouceine OUHAMZA
 
Twins: OOP and FP
RichardWarburton
 
A Brief Introduction to the Qt Application Framework
Zachary Blair
 
DLL Design with Building Blocks
Max Kleiner
 
OpenGL Fixed Function to Shaders - Porting a fixed function application to “m...
ICS
 
Android JNI
Siva Ramakrishna kv
 
Qt Workshop
Johan Thelin
 
Untitled presentation(4)
chan20kaur
 
What Makes Objective C Dynamic?
Kyle Oba
 

Similar to Objective-C Runtime overview (20)

PDF
Pavel kravchenko obj c runtime
DneprCiklumEvents
 
PDF
The Dark Side of Objective-C
Martin Kiss
 
PDF
Objc
Pragati Singh
 
PDF
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
e-Legion
 
PPTX
Objective-c Runtime
Pavel Albitsky
 
PDF
Objective c runtime
Inferis
 
PPT
Objective c intro (1)
David Echeverria
 
PPT
iOS Application Development
Compare Infobase Limited
 
PPTX
Presentation 1st
Connex
 
PPTX
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
NicheTech Com. Solutions Pvt. Ltd.
 
PPTX
Objective-c for Java Developers
Muhammad Abdullah
 
PPTX
Presentation 3rd
Connex
 
PDF
Никита Корчагин - Programming Apple iOS with Objective-C
DataArt
 
PDF
01 objective-c session 1
Amr Elghadban (AmrAngry)
 
PPT
Cocoa for Web Developers
georgebrock
 
PPTX
Ios fundamentals with ObjectiveC
Madusha Perera
 
PDF
Intro to Objective C
Ashiq Uz Zoha
 
PDF
Introduction to objective c
Sunny Shaikh
 
PPT
Objective-C for iOS Application Development
Dhaval Kaneria
 
PDF
Programming with Objective-C
Nagendra Ram
 
Pavel kravchenko obj c runtime
DneprCiklumEvents
 
The Dark Side of Objective-C
Martin Kiss
 
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
e-Legion
 
Objective-c Runtime
Pavel Albitsky
 
Objective c runtime
Inferis
 
Objective c intro (1)
David Echeverria
 
iOS Application Development
Compare Infobase Limited
 
Presentation 1st
Connex
 
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
NicheTech Com. Solutions Pvt. Ltd.
 
Objective-c for Java Developers
Muhammad Abdullah
 
Presentation 3rd
Connex
 
Никита Корчагин - Programming Apple iOS with Objective-C
DataArt
 
01 objective-c session 1
Amr Elghadban (AmrAngry)
 
Cocoa for Web Developers
georgebrock
 
Ios fundamentals with ObjectiveC
Madusha Perera
 
Intro to Objective C
Ashiq Uz Zoha
 
Introduction to objective c
Sunny Shaikh
 
Objective-C for iOS Application Development
Dhaval Kaneria
 
Programming with Objective-C
Nagendra Ram
 
Ad

Recently uploaded (20)

PDF
Continouous failure - Why do we make our lives hard?
Papp Krisztián
 
PDF
Power BI vs Tableau vs Looker - Which BI Tool is Right for You?
MagnusMinds IT Solution LLP
 
PPTX
NeuroStrata: Harnessing Neuro-Symbolic Paradigms for Improved Testability and...
Ivan Ruchkin
 
PPTX
CV-Project_2024 version 01222222222.pptx
MohammadSiddiqui70
 
PPTX
CONCEPT OF PROGRAMMING in language .pptx
tamim41
 
PDF
IDM Crack with Internet Download Manager 6.42 Build 41
utfefguu
 
PDF
How DeepSeek Beats ChatGPT: Cost Comparison and Key Differences
sumitpurohit810
 
PDF
What Is an Internal Quality Audit and Why It Matters for Your QMS
BizPortals365
 
PPTX
Perfecting XM Cloud for Multisite Setup.pptx
Ahmed Okour
 
PDF
Writing Maintainable Playwright Tests with Ease
Shubham Joshi
 
PPTX
Automatic_Iperf_Log_Result_Excel_visual_v2.pptx
Chen-Chih Lee
 
PPTX
Introduction to web development | MERN Stack
JosephLiyon
 
PPTX
IDM Crack with Internet Download Manager 6.42 [Latest 2025]
HyperPc soft
 
PDF
Dealing with JSON in the relational world
Andres Almiray
 
PPTX
ERP - FICO Presentation BY BSL BOKARO STEEL LIMITED.pptx
ravisranjan
 
PDF
AI Software Development Process, Strategies and Challenges
Net-Craft.com
 
PPTX
Seamless-Image-Conversion-From-Raster-to-wrt-rtx-rtx.pptx
Quick Conversion Services
 
PDF
Telemedicine App Development_ Key Factors to Consider for Your Healthcare Ven...
Mobilityinfotech
 
PDF
Designing Accessible Content Blocks (1).pdf
jaclynmennie1
 
PDF
IObit Uninstaller Pro 14.3.1.8 Crack for Windows Latest
utfefguu
 
Continouous failure - Why do we make our lives hard?
Papp Krisztián
 
Power BI vs Tableau vs Looker - Which BI Tool is Right for You?
MagnusMinds IT Solution LLP
 
NeuroStrata: Harnessing Neuro-Symbolic Paradigms for Improved Testability and...
Ivan Ruchkin
 
CV-Project_2024 version 01222222222.pptx
MohammadSiddiqui70
 
CONCEPT OF PROGRAMMING in language .pptx
tamim41
 
IDM Crack with Internet Download Manager 6.42 Build 41
utfefguu
 
How DeepSeek Beats ChatGPT: Cost Comparison and Key Differences
sumitpurohit810
 
What Is an Internal Quality Audit and Why It Matters for Your QMS
BizPortals365
 
Perfecting XM Cloud for Multisite Setup.pptx
Ahmed Okour
 
Writing Maintainable Playwright Tests with Ease
Shubham Joshi
 
Automatic_Iperf_Log_Result_Excel_visual_v2.pptx
Chen-Chih Lee
 
Introduction to web development | MERN Stack
JosephLiyon
 
IDM Crack with Internet Download Manager 6.42 [Latest 2025]
HyperPc soft
 
Dealing with JSON in the relational world
Andres Almiray
 
ERP - FICO Presentation BY BSL BOKARO STEEL LIMITED.pptx
ravisranjan
 
AI Software Development Process, Strategies and Challenges
Net-Craft.com
 
Seamless-Image-Conversion-From-Raster-to-wrt-rtx-rtx.pptx
Quick Conversion Services
 
Telemedicine App Development_ Key Factors to Consider for Your Healthcare Ven...
Mobilityinfotech
 
Designing Accessible Content Blocks (1).pdf
jaclynmennie1
 
IObit Uninstaller Pro 14.3.1.8 Crack for Windows Latest
utfefguu
 
Ad

Objective-C Runtime overview

  • 1. Objective C Runtime Khoa Pham 2359Media
  • 2. Today ● self = [super init] ● objc_msgSend ● ObjC Runtime ● How to use the Runtime API ● Use cases
  • 3. self = [super init] ETPAnimal *cat = [ETPAnimal cat]; NSInteger recordCount = [ETPCoreDataManager recordCount];
  • 4. self = [super init] @interface ETPCat : ETPAnimal @end ETPCat *cat = [[ETPCat alloc] init]
  • 5. self = [super init] - (id)init { self = [super init]; if (self) { // ETPCat does it own initialization here } return self; }
  • 6. self = [super init] [super init] calls the superclass implementation of init with the (hidden) self argument. It can do one of these things + set some properties on self, and return self + return a different object (factory, singleton) + return nil
  • 7. self = [super init] ETPCat *cat = [ETPCat alloc] // 0x1111111a [cat init] // 0x1111111b [cat meomeo] // 0x1111111a
  • 8. self = [super init] Demo
  • 9. objc_msgSend ETPCat *cat = [[ETPCat alloc] init] [cat setName:@”meo”] objc_msgSend(cat, @selector(setName:), @”meo”)
  • 12. @selector SEL selector1 = @selector(initWithName:) SEL selector2 = @selector(initWithFriends1Name::) typedef struct objc_selector *SEL Read more at Objective C Runtime Reference -> Data Structure -> Class definition Data structure -> SEL
  • 14. Objective C Runtime The Objective-C Runtime is a Runtime Library, it's a library written mainly in C & Assembler that adds the Object Oriented capabilities to C to create Objective-C.
  • 15. Objective C Runtime Source code http://www.opensource.apple. com/source/objc4/objc4-532/runtime/objc-class.mm There are two versions of the Objective-C runtime— “modern” and “legacy”. The modern version was introduced with Objective-C 2.0 and includes a number of new features.
  • 16. Objective C Runtime Dynamic feature Object oriented capability
  • 17. Objective C Runtime Features ● Class elements (categories, methods, variables, property, …) ● Object ● Messaging ● Object introspection
  • 18. Objective C Runtime @interface ETPAnimal : NSObject @end typedef struct objc_class *Class;
  • 19. Objective C Runtime (old) struct objc_class { Class isa; Class super_class OBJC2_UNAVAILABLE; const char *name OBJC2_UNAVAILABLE; long version OBJC2_UNAVAILABLE; long info OBJC2_UNAVAILABLE; long instance_size OBJC2_UNAVAILABLE; struct objc_ivar_list *ivars OBJC2_UNAVAILABLE; struct objc_method_list **methodLists OBJC2_UNAVAILABLE; struct objc_cache *cache OBJC2_UNAVAILABLE; struct objc_protocol_list *protocols OBJC2_UNAVAILABLE; }
  • 20. Objective C Runtime typedef struct class_ro_t { const char * name; const ivar_list_t * ivars; } class_ro_t typedef struct class_rw_t { const class_ro_t *ro; method_list_t **methods; struct class_t *firstSubclass; struct class_t *nextSiblingClass; } class_rw_t;
  • 21. Objective C Runtime ETPAnimal *animal = [[ETPAnimal alloc] init] struct objc_object { Class isa; // variables };
  • 22. Objective C Runtime id someAnimal = [[ETPAnimal alloc] init] typedef struct objc_object { Class isa; } *id;
  • 23. Objective C Runtime Class is also an object, its isa pointer points to its meta class The metaclass is the description of the class object
  • 27. Objective C Runtime ● Dynamic typing ● Dynamic binding ● Dynamic method resolution ● Introspection
  • 28. Objective C Runtime Dynamic typing Dynamic typing enables the runtime to determine the type of an object at runtime id cat = [[ETPCat alloc] init] - (void)acceptAnything:(id)anything;
  • 29. Objective C Runtime Dynamic binding Dynamic binding is the process of mapping a message to a method at runtime, rather than at compile time
  • 30. Objective C Runtime Dynamic method resolution Provide the implementation of a method dynamically. @dynamic
  • 32. How to use the Runtime API Objective-C programs interact with the runtime system to implement the dynamic features of the language. ● Objective-C source code ● Foundation Framework NSObject methods ● Runtime library API
  • 33. Use cases Method swizzle (IIViewDeckController) JSON Model (Torin ‘s BaseModel) Message forwarding Meta programming
  • 35. Use cases Method swizzle (IIViewDeckController) SEL presentVC = @selector(presentViewController:animated:completion:); SEL vdcPresentVC = @selector(vdc_presentViewController:animated:completion:); method_exchangeImplementations(class_getInstanceMethod(self, presentVC), class_getInstanceMethod(self, vdcPresentVC));
  • 36. Use cases Method swizzle (IIViewDeckController) - (void)vdc_presentViewController:(UIViewController *)viewControllerToPresent animated:(BOOL) animated completion:(void (^)(void))completion { UIViewController* controller = self.viewDeckController ?: self; [controller vdc_presentViewController:viewControllerToPresent animated:animated completion: completion]; // when we get here, the vdc_ method is actually the old, real method }
  • 37. Use cases JSON Model (Torin ‘s BaseModel) updateWithDictionary class_copyIvarList ivar_getName
  • 38. Use cases JSON Model (Torin ‘s BaseModel) @interface ETPItem : BaseModel @property (nonatomic, copy) NSString * ID; @property (nonatomic, copy) NSString *name; @end ETPItem *item = [[ETPItem alloc] init]; [item updateWithDictionary:@{@”ID”: @”1”, @”name”: @”item1”}];
  • 40. Use cases Meta programming ● Dynamic method naming ● Validation ● Template ● Mocking
  • 41. Reference 1. http://cocoasamurai.blogspot.com/2010/01/understanding-objective-c-runtime.html 2. http://www.slideshare.net/mudphone/what-makes-objective-c-dynamic 3. http://www.cocoawithlove.com/2009/04/what-does-it-mean-when-you-assign-super.html 4. http://nshipster.com/method-swizzling/ 5. http://stackoverflow.com/questions/415452/object-orientation-in-c 6. http://stackoverflow.com/questions/2766233/what-is-the-c-runtime-library 7. http://gcc.gnu.org/onlinedocs/gcc/Modern-GNU-Objective-C-runtime-API.html 8. http://www.opensource.apple.com/source/objc4/objc4-532/runtime/objc-class.mm 9. http://www.friday.com/bbum/2009/12/18/objc_msgsend-part-1-the-road-map/ 10. https://www.mikeash.com/pyblog/friday-qa-2010-01-29-method-replacement-for-fun-and-profit.html 11. Pro Objective C, chapter 7, 8, 9 12. Effective Objective C, chapter 2 13. http://wiki.gnustep.org/index.php/ObjC2_FAQ