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

英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
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
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
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.
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
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
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfIdiosysTechnologies1
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
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
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 

Recently uploaded (20)

英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
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
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
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
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
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...
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdf
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
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
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 

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