SlideShare a Scribd company logo
1 of 42
Download to read offline
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
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

GPU Programming on CPU - Using C++AMP
GPU Programming on CPU - Using C++AMPGPU Programming on CPU - Using C++AMP
GPU Programming on CPU - Using C++AMPMiller Lee
 
QThreads: Are You Using Them Wrong?
QThreads: Are You Using Them Wrong? QThreads: Are You Using Them Wrong?
QThreads: Are You Using Them Wrong? ICS
 
Qt multi threads
Qt multi threadsQt multi threads
Qt multi threadsYnon Perek
 
Java 14 features
Java 14 featuresJava 14 features
Java 14 featuresAditi Anand
 
Native code in Android applications
Native code in Android applicationsNative code in Android applications
Native code in Android applicationsDmitry Matyukhin
 
C++ amp on linux
C++ amp on linuxC++ amp on linux
C++ amp on linuxMiller Lee
 
A Brief Introduction to the Qt Application Framework
A Brief Introduction to the Qt Application FrameworkA Brief Introduction to the Qt Application Framework
A Brief Introduction to the Qt Application FrameworkZachary Blair
 
DLL Design with Building Blocks
DLL Design with Building BlocksDLL Design with Building Blocks
DLL Design with Building BlocksMax Kleiner
 
OpenGL Fixed Function to Shaders - Porting a fixed function application to “m...
OpenGL Fixed Function to Shaders - Porting a fixed function application to “m...OpenGL Fixed Function to Shaders - Porting a fixed function application to “m...
OpenGL Fixed Function to Shaders - Porting a fixed function application to “m...ICS
 
Untitled presentation(4)
Untitled presentation(4)Untitled presentation(4)
Untitled presentation(4)chan20kaur
 
What Makes Objective C Dynamic?
What Makes Objective C Dynamic?What Makes Objective C Dynamic?
What Makes Objective C Dynamic?Kyle Oba
 

What's hot (20)

GPU Programming on CPU - Using C++AMP
GPU Programming on CPU - Using C++AMPGPU Programming on CPU - Using C++AMP
GPU Programming on CPU - Using C++AMP
 
QThreads: Are You Using Them Wrong?
QThreads: Are You Using Them Wrong? QThreads: Are You Using Them Wrong?
QThreads: Are You Using Them Wrong?
 
Progress_190412
Progress_190412Progress_190412
Progress_190412
 
Vulkan 1.1 Reference Guide
Vulkan 1.1 Reference GuideVulkan 1.1 Reference Guide
Vulkan 1.1 Reference Guide
 
Qt multi threads
Qt multi threadsQt multi threads
Qt multi threads
 
Runtime
RuntimeRuntime
Runtime
 
Java 14 features
Java 14 featuresJava 14 features
Java 14 features
 
Qt for beginners
Qt for beginnersQt for beginners
Qt for beginners
 
Native code in Android applications
Native code in Android applicationsNative code in Android applications
Native code in Android applications
 
C++ amp on linux
C++ amp on linuxC++ amp on linux
C++ amp on linux
 
OpenGL SC 2.0 Quick Reference
OpenGL SC 2.0 Quick ReferenceOpenGL SC 2.0 Quick Reference
OpenGL SC 2.0 Quick Reference
 
Complete Java Course
Complete Java CourseComplete Java Course
Complete Java Course
 
Twins: OOP and FP
Twins: OOP and FPTwins: OOP and FP
Twins: OOP and FP
 
A Brief Introduction to the Qt Application Framework
A Brief Introduction to the Qt Application FrameworkA Brief Introduction to the Qt Application Framework
A Brief Introduction to the Qt Application Framework
 
DLL Design with Building Blocks
DLL Design with Building BlocksDLL Design with Building Blocks
DLL Design with Building Blocks
 
OpenGL Fixed Function to Shaders - Porting a fixed function application to “m...
OpenGL Fixed Function to Shaders - Porting a fixed function application to “m...OpenGL Fixed Function to Shaders - Porting a fixed function application to “m...
OpenGL Fixed Function to Shaders - Porting a fixed function application to “m...
 
Android JNI
Android JNIAndroid JNI
Android JNI
 
Qt Workshop
Qt WorkshopQt Workshop
Qt Workshop
 
Untitled presentation(4)
Untitled presentation(4)Untitled presentation(4)
Untitled presentation(4)
 
What Makes Objective C Dynamic?
What Makes Objective C Dynamic?What Makes Objective C Dynamic?
What Makes Objective C Dynamic?
 

Similar to Objective-C Runtime overview

Разработка кросс-платформенного кода между iPhone < -> Windows с помощью o...
Разработка кросс-платформенного кода между iPhone < -> Windows с помощью o...Разработка кросс-платформенного кода между iPhone < -> Windows с помощью o...
Разработка кросс-платформенного кода между iPhone < -> Windows с помощью o...Yandex
 
Open Cv 2005 Q4 Tutorial
Open Cv 2005 Q4 TutorialOpen Cv 2005 Q4 Tutorial
Open Cv 2005 Q4 Tutorialantiw
 
iOS,From Development to Distribution
iOS,From Development to DistributioniOS,From Development to Distribution
iOS,From Development to DistributionTunvir Rahman Tusher
 
How to instantiate any view controller for free
How to instantiate any view controller for freeHow to instantiate any view controller for free
How to instantiate any view controller for freeBenotCaron
 
Daggerate your code - Write your own annotation processor
Daggerate your code - Write your own annotation processorDaggerate your code - Write your own annotation processor
Daggerate your code - Write your own annotation processorBartosz Kosarzycki
 
Java programming concept
Java programming conceptJava programming concept
Java programming conceptSanjay Gunjal
 
The Ring programming language version 1.2 book - Part 51 of 84
The Ring programming language version 1.2 book - Part 51 of 84The Ring programming language version 1.2 book - Part 51 of 84
The Ring programming language version 1.2 book - Part 51 of 84Mahmoud Samir Fayed
 
iOS 101 - Xcode, Objective-C, iOS APIs
iOS 101 - Xcode, Objective-C, iOS APIsiOS 101 - Xcode, Objective-C, iOS APIs
iOS 101 - Xcode, Objective-C, iOS APIsSubhransu Behera
 
How to Connect SystemVerilog with Octave
How to Connect SystemVerilog with OctaveHow to Connect SystemVerilog with Octave
How to Connect SystemVerilog with OctaveAmiq Consulting
 
From C++ to Objective-C
From C++ to Objective-CFrom C++ to Objective-C
From C++ to Objective-Ccorehard_by
 
The Ring programming language version 1.7 book - Part 75 of 196
The Ring programming language version 1.7 book - Part 75 of 196The Ring programming language version 1.7 book - Part 75 of 196
The Ring programming language version 1.7 book - Part 75 of 196Mahmoud Samir Fayed
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The LandingHaci Murat Yaman
 
The Ring programming language version 1.8 book - Part 77 of 202
The Ring programming language version 1.8 book - Part 77 of 202The Ring programming language version 1.8 book - Part 77 of 202
The Ring programming language version 1.8 book - Part 77 of 202Mahmoud Samir Fayed
 
Working with Cocoa and Objective-C
Working with Cocoa and Objective-CWorking with Cocoa and Objective-C
Working with Cocoa and Objective-CKazunobu Tasaka
 
React Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsReact Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsMatteo Manchi
 
Suite Script 2.0 API Basics
Suite Script 2.0 API BasicsSuite Script 2.0 API Basics
Suite Script 2.0 API BasicsJimmy Butare
 
iOS overview
iOS overviewiOS overview
iOS overviewgupta25
 

Similar to Objective-C Runtime overview (20)

Разработка кросс-платформенного кода между iPhone < -> Windows с помощью o...
Разработка кросс-платформенного кода между iPhone < -> Windows с помощью o...Разработка кросс-платформенного кода между iPhone < -> Windows с помощью o...
Разработка кросс-платформенного кода между iPhone < -> Windows с помощью o...
 
Open Cv 2005 Q4 Tutorial
Open Cv 2005 Q4 TutorialOpen Cv 2005 Q4 Tutorial
Open Cv 2005 Q4 Tutorial
 
Objective c intro (1)
Objective c intro (1)Objective c intro (1)
Objective c intro (1)
 
iOS,From Development to Distribution
iOS,From Development to DistributioniOS,From Development to Distribution
iOS,From Development to Distribution
 
How to instantiate any view controller for free
How to instantiate any view controller for freeHow to instantiate any view controller for free
How to instantiate any view controller for free
 
Daggerate your code - Write your own annotation processor
Daggerate your code - Write your own annotation processorDaggerate your code - Write your own annotation processor
Daggerate your code - Write your own annotation processor
 
Java programming concept
Java programming conceptJava programming concept
Java programming concept
 
The Ring programming language version 1.2 book - Part 51 of 84
The Ring programming language version 1.2 book - Part 51 of 84The Ring programming language version 1.2 book - Part 51 of 84
The Ring programming language version 1.2 book - Part 51 of 84
 
iOS 101 - Xcode, Objective-C, iOS APIs
iOS 101 - Xcode, Objective-C, iOS APIsiOS 101 - Xcode, Objective-C, iOS APIs
iOS 101 - Xcode, Objective-C, iOS APIs
 
MattsonTutorialSC14.pdf
MattsonTutorialSC14.pdfMattsonTutorialSC14.pdf
MattsonTutorialSC14.pdf
 
How to Connect SystemVerilog with Octave
How to Connect SystemVerilog with OctaveHow to Connect SystemVerilog with Octave
How to Connect SystemVerilog with Octave
 
From C++ to Objective-C
From C++ to Objective-CFrom C++ to Objective-C
From C++ to Objective-C
 
The Ring programming language version 1.7 book - Part 75 of 196
The Ring programming language version 1.7 book - Part 75 of 196The Ring programming language version 1.7 book - Part 75 of 196
The Ring programming language version 1.7 book - Part 75 of 196
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The Landing
 
Android ndk
Android ndkAndroid ndk
Android ndk
 
The Ring programming language version 1.8 book - Part 77 of 202
The Ring programming language version 1.8 book - Part 77 of 202The Ring programming language version 1.8 book - Part 77 of 202
The Ring programming language version 1.8 book - Part 77 of 202
 
Working with Cocoa and Objective-C
Working with Cocoa and Objective-CWorking with Cocoa and Objective-C
Working with Cocoa and Objective-C
 
React Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsReact Native for multi-platform mobile applications
React Native for multi-platform mobile applications
 
Suite Script 2.0 API Basics
Suite Script 2.0 API BasicsSuite Script 2.0 API Basics
Suite Script 2.0 API Basics
 
iOS overview
iOS overviewiOS overview
iOS overview
 

Recently uploaded

Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 

Recently uploaded (20)

Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 

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
  • 25.
  • 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