SlideShare une entreprise Scribd logo
1  sur  24
Télécharger pour lire hors ligne
Objective-C Runtime
    Pavel Kravchenko,
         Ciklum
Agenda

   What is runtime?
   How we can use runtime?
   How does it work?
   What is object, class, isa, metaclass?
   What can we do with runtime?
What is it?


The runtime system acts as a kind of
 operating system for the Objective-C
 language
Purpose
- understanding basic principles
- some useful things (class method,
  respondsToSelector, etc) → more simple,
  effective & understandable code
- tricks (dynamic loading, change of method
   implementation, simulation of multiple
   inheritance)
Interacting with Runtime


through Objective-C source code


through NSObject methods


and through direct calls to runtime
NSObject methods

class
IsKindOfClass:
IsMemberOfClass:
RespondsToSelector:
ConformsToProtocol:
MethodForSelector:
Runtime methods

class_addMethod
class_replaceMethod
objc_setAssociatedObject
objc_getAssociatedObject
method_setImplementation
method_exchangeImplementations
Basic Types
typedef struct objc_selector        *SEL;

typedef struct objc_class *Class;

typedef struct objc_object {

    Class isa;

} *id

struct objc_class {

    Class isa;

    Class super_class;

}

struct objc_method {

    SEL method_name;

    char *method_types;

    IMP method_imp;

}
Classes and
metaclasses
Messaging
Messaging

   [target method:arg1 :arg2] →
    objc_msgSend(target, selector, arg1, arg2)


   SEL selector = @selector(method::);


   SEL is unique identifier of the method name
Messaging

■ It first finds the method implementation that the selector
  refers to.
■ It then calls the procedure, passing it the receiving object,
  along with any arguments that were specified for the
  method.
■ Finally, it passes on the return value of the procedure as its
  own return value.
Dynamic Method Resolution
void dynamicMethodIMP(id self, SEL _cmd) {
    // implementation ....
}
+ (BOOL) resolveInstanceMethod:(SEL) aSEL {
    if (aSEL == @selector(resolveThisMethodDynamically)) {
    class_addMethod([self class], aSEL, (IMP)
    dynamicMethodIMP, "v@:");
        return YES;
    }
    return [super resolveInstanceMethod:aSEL];
}
Message Forwarding
2011-03-26 07:32:26.268 First[48403:207] *** Terminating app due to uncaught exception
   'NSInvalidArgumentException', reason: '-[NSCFString setObject:forKey:]: unrecognized selector sent
   to instance 0x4e0cc70'

*** Call stack at first throw:

(

0 CoreFoundation                   0x00db4be9 __exceptionPreprocess + 185

1 libobjc.A.dylib                0x00f095c2 objc_exception_throw + 47

2 CoreFoundation                   0x00db66fb -[NSObject(NSObject) doesNotRecognizeSelector:] + 187

3 CoreFoundation                   0x00d26366 ___forwarding___ + 966

4 CoreFoundation                   0x00d25f22 _CF_forwarding_prep_0 + 50

5 First                     0x00002616 -[My1 newM] + 101

6 First                     0x00001f00 -[My1 mySelector] + 50
Message Forwarding
   Sending a message to object that does not
    handle it is an error
   Before error (crash) runtime gives the receiving
    object second chance to handle wrong
    message
   We need to implement methods of another
    class, but cannot subclass it
Message Forwarding
Message Forwarding
- (void)forwardInvocation:(NSInvocation *)
  anInvocation {
      if ([someOtherObject respondsToSelector:
    [anInvocation selector]])
          [anInvocation
    invokeWithTarget:someOtherObject];
      else
          [super forwardInvocation:anInvocation];
}
Message Forwarding
@implementation NSObject (NoCrash)

- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector

{

    NSMethodSignature *methodSignature = [NSMethodSignature
     signatureWithObjCTypes:"v@:"];

    return methodSignature;

}

- (void) forwardInvocation:(NSInvocation *)anInvocation

{

}
Tricks
id classObj = objc_getClass("SomeClass");
unsigned int outCount, i;
objc_property_t *properties = class_copyPropertyList(classObj,
   &outCount);
for (i = 0; i < outCount; i++) {
    objc_property_t property = properties[i];
    NSString *selector = [NSString
    stringWithCString:property_getName(property)];
    SEL selForProperty = NSSelectorFromString(selector);
    NSLog(@"%@", [self performSelector:selForProperty]);
}
KVO
   Automatic key-value observing is implemented using a
    technique called isa-swizzling.
   What KVO does when you request to observe some property:
1. Gets the class of the object
2. Creates a new subclass of the object's class
3. Overrides the -class method with one that returns the Class of
   the original class
4. Overrides the desired setter methods in the original class
5. Sets the isa variable of the object to the new subclass
Method swizzling
DataObject * dataObject = [[DataObject alloc]
  init];
[dataObject addObserver:self
  forKeyPath:@"dataValue" options:0
  context:NULL];
NSLog(@"%@", [dataObject class]);     //logs
  "DataObject"
NSLog(@"%@", object_getClass(dataObject));
  //logs "NSKVONotifying_DataObject"
Method swizzling
Method existingMethod = class_getInstanceMethod([self class],
  @selector(viewDidLoad));

Method myNewMethod = class_getInstanceMethod([self class],
  @selector(viewDidLoadMy));

method_exchangeImplementations(existingMethod, myNewMethod);



@implementation UIViewController (someCategory)

- (void) viewDidLoadMy

{

    [self viewDidLoadMy];

    NSLog(@"Print info");

}
Links
   http://touchdev.ru/documents/958
   http://www.sealiesoftware.com/blog/archive/200
    9/04/14/objc_explain_Classes_and_metaclasse
    s.html
   http://cocoawithlove.com/2010/01/what-is-meta-
    class-in-objective-c.html
   http://cocoasamurai.blogspot.com/2010/01/und
    erstanding-objective-c-runtime.html
   Objective C Runtime Programming Guide
   Objective C Runtime Reference
About me
       Pavel Kravchenko
       skype:
        ideateam_macuser
       email:
    kravchenkopo@gmail.com


       Interests:
       iOS, Android, security
       Manadgment

Contenu connexe

Tendances

Modul Praktek Java OOP
Modul Praktek Java OOP Modul Praktek Java OOP
Modul Praktek Java OOP Zaenal Arifin
 
Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCOUM SAOKOSAL
 
Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)Alok Kumar
 
Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarROHIT JAISWAR
 
Java OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - CollectionJava OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - CollectionOUM SAOKOSAL
 
constructors in java ppt
constructors in java pptconstructors in java ppt
constructors in java pptkunal kishore
 
Constructor&method
Constructor&methodConstructor&method
Constructor&methodJani Harsh
 
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12Abu Saleh
 
Advanced Java - Praticals
Advanced Java - PraticalsAdvanced Java - Praticals
Advanced Java - PraticalsFahad Shaikh
 
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้นคลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้นFinian Nian
 
The Ring programming language version 1.8 book - Part 36 of 202
The Ring programming language version 1.8 book - Part 36 of 202The Ring programming language version 1.8 book - Part 36 of 202
The Ring programming language version 1.8 book - Part 36 of 202Mahmoud Samir Fayed
 

Tendances (20)

Lecture 7 arrays
Lecture   7 arraysLecture   7 arrays
Lecture 7 arrays
 
Modul Praktek Java OOP
Modul Praktek Java OOP Modul Praktek Java OOP
Modul Praktek Java OOP
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
 
Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBC
 
Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)
 
Class method
Class methodClass method
Class method
 
Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswar
 
Javascript
JavascriptJavascript
Javascript
 
Java OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - CollectionJava OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - Collection
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
 
constructors in java ppt
constructors in java pptconstructors in java ppt
constructors in java ppt
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Constructor&method
Constructor&methodConstructor&method
Constructor&method
 
Java Basic day-2
Java Basic day-2Java Basic day-2
Java Basic day-2
 
Java Programming - 03 java control flow
Java Programming - 03 java control flowJava Programming - 03 java control flow
Java Programming - 03 java control flow
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
 
Advanced Java - Praticals
Advanced Java - PraticalsAdvanced Java - Praticals
Advanced Java - Praticals
 
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้นคลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
 
The Ring programming language version 1.8 book - Part 36 of 202
The Ring programming language version 1.8 book - Part 36 of 202The Ring programming language version 1.8 book - Part 36 of 202
The Ring programming language version 1.8 book - Part 36 of 202
 

En vedette

Dmitry pilipenko i os gamekit
Dmitry pilipenko i os gamekitDmitry pilipenko i os gamekit
Dmitry pilipenko i os gamekitDneprCiklumEvents
 
Winactie kleurplaten
Winactie kleurplatenWinactie kleurplaten
Winactie kleurplatenvdwvm
 
05 net saturday vasiliy borovyak ''.net performance nontrivial bottlenecks''
05 net saturday vasiliy borovyak ''.net performance nontrivial bottlenecks''05 net saturday vasiliy borovyak ''.net performance nontrivial bottlenecks''
05 net saturday vasiliy borovyak ''.net performance nontrivial bottlenecks''DneprCiklumEvents
 
Kirill Zotin клиент серверное взаимодействие под android в деталях
Kirill Zotin клиент серверное взаимодействие под android в деталяхKirill Zotin клиент серверное взаимодействие под android в деталях
Kirill Zotin клиент серверное взаимодействие под android в деталяхDneprCiklumEvents
 
Time management training (Vadim Tikanov Ciklum)
Time management training (Vadim Tikanov Ciklum)Time management training (Vadim Tikanov Ciklum)
Time management training (Vadim Tikanov Ciklum)DneprCiklumEvents
 
Alfa times 1
Alfa times 1Alfa times 1
Alfa times 1tompce
 
Segey Glebov tips and tricks for modern mobile project management
Segey Glebov tips and tricks for modern mobile project managementSegey Glebov tips and tricks for modern mobile project management
Segey Glebov tips and tricks for modern mobile project managementDneprCiklumEvents
 

En vedette (8)

Dmitry pilipenko i os gamekit
Dmitry pilipenko i os gamekitDmitry pilipenko i os gamekit
Dmitry pilipenko i os gamekit
 
Winactie kleurplaten
Winactie kleurplatenWinactie kleurplaten
Winactie kleurplaten
 
05 net saturday vasiliy borovyak ''.net performance nontrivial bottlenecks''
05 net saturday vasiliy borovyak ''.net performance nontrivial bottlenecks''05 net saturday vasiliy borovyak ''.net performance nontrivial bottlenecks''
05 net saturday vasiliy borovyak ''.net performance nontrivial bottlenecks''
 
Kirill Zotin клиент серверное взаимодействие под android в деталях
Kirill Zotin клиент серверное взаимодействие под android в деталяхKirill Zotin клиент серверное взаимодействие под android в деталях
Kirill Zotin клиент серверное взаимодействие под android в деталях
 
Taras Kalapun ui testing
Taras Kalapun ui testingTaras Kalapun ui testing
Taras Kalapun ui testing
 
Time management training (Vadim Tikanov Ciklum)
Time management training (Vadim Tikanov Ciklum)Time management training (Vadim Tikanov Ciklum)
Time management training (Vadim Tikanov Ciklum)
 
Alfa times 1
Alfa times 1Alfa times 1
Alfa times 1
 
Segey Glebov tips and tricks for modern mobile project management
Segey Glebov tips and tricks for modern mobile project managementSegey Glebov tips and tricks for modern mobile project management
Segey Glebov tips and tricks for modern mobile project management
 

Similaire à Pavel kravchenko obj c runtime

Dynamic Swift
Dynamic SwiftDynamic Swift
Dynamic SwiftSaul Mora
 
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.pptDESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.pptAntoJoseph36
 
11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objectsPhúc Đỗ
 
From C++ to Objective-C
From C++ to Objective-CFrom C++ to Objective-C
From C++ to Objective-Ccorehard_by
 
The Dark Side of Objective-C
The Dark Side of Objective-CThe Dark Side of Objective-C
The Dark Side of Objective-CMartin Kiss
 
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
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxchetanpatilcp783
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethodsdreampuf
 
Ios development
Ios developmentIos development
Ios developmentelnaqah
 
Objective-C Runtime overview
Objective-C Runtime overviewObjective-C Runtime overview
Objective-C Runtime overviewFantageek
 
How to build an AOP framework in ActionScript
How to build an AOP framework in ActionScriptHow to build an AOP framework in ActionScript
How to build an AOP framework in ActionScriptChristophe Herreman
 
The Ring programming language version 1.5.2 book - Part 37 of 181
The Ring programming language version 1.5.2 book - Part 37 of 181The Ring programming language version 1.5.2 book - Part 37 of 181
The Ring programming language version 1.5.2 book - Part 37 of 181Mahmoud Samir Fayed
 
Infinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho Poluta
Infinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho PolutaInfinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho Poluta
Infinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho PolutaInfinum
 
COScheduler In Depth
COScheduler In DepthCOScheduler In Depth
COScheduler In DepthWO Community
 

Similaire à Pavel kravchenko obj c runtime (20)

Objective-c Runtime
Objective-c RuntimeObjective-c Runtime
Objective-c Runtime
 
Dynamic Swift
Dynamic SwiftDynamic Swift
Dynamic Swift
 
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.pptDESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
 
Runtime
RuntimeRuntime
Runtime
 
11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objects
 
From C++ to Objective-C
From C++ to Objective-CFrom C++ to Objective-C
From C++ to Objective-C
 
nested_Object as Parameter & Recursion_Later_commamd.pptx
nested_Object as Parameter  & Recursion_Later_commamd.pptxnested_Object as Parameter  & Recursion_Later_commamd.pptx
nested_Object as Parameter & Recursion_Later_commamd.pptx
 
The Dark Side of Objective-C
The Dark Side of Objective-CThe Dark Side of Objective-C
The Dark Side of Objective-C
 
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
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethods
 
Ios development
Ios developmentIos development
Ios development
 
Objective c
Objective cObjective c
Objective c
 
Objective-C Runtime overview
Objective-C Runtime overviewObjective-C Runtime overview
Objective-C Runtime overview
 
How to build an AOP framework in ActionScript
How to build an AOP framework in ActionScriptHow to build an AOP framework in ActionScript
How to build an AOP framework in ActionScript
 
The Ring programming language version 1.5.2 book - Part 37 of 181
The Ring programming language version 1.5.2 book - Part 37 of 181The Ring programming language version 1.5.2 book - Part 37 of 181
The Ring programming language version 1.5.2 book - Part 37 of 181
 
Infinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho Poluta
Infinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho PolutaInfinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho Poluta
Infinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho Poluta
 
Getting Input from User
Getting Input from UserGetting Input from User
Getting Input from User
 
Unit-2 Getting Input from User.pptx
Unit-2 Getting Input from User.pptxUnit-2 Getting Input from User.pptx
Unit-2 Getting Input from User.pptx
 
COScheduler In Depth
COScheduler In DepthCOScheduler In Depth
COScheduler In Depth
 

Plus de DneprCiklumEvents

Convert estimates to plans (Maxym Mykhalchuk Ciklum)
Convert estimates to plans (Maxym Mykhalchuk Ciklum)Convert estimates to plans (Maxym Mykhalchuk Ciklum)
Convert estimates to plans (Maxym Mykhalchuk Ciklum)DneprCiklumEvents
 
Vladimir kozhayev handmade isometry
Vladimir kozhayev handmade isometryVladimir kozhayev handmade isometry
Vladimir kozhayev handmade isometryDneprCiklumEvents
 
Pavel yuriychuk svg in game development
Pavel yuriychuk svg in game developmentPavel yuriychuk svg in game development
Pavel yuriychuk svg in game developmentDneprCiklumEvents
 
Vitaly hit' abc_of_game_development
Vitaly hit' abc_of_game_developmentVitaly hit' abc_of_game_development
Vitaly hit' abc_of_game_developmentDneprCiklumEvents
 
04 net saturday eugene sukhikh ''the basic performance questions''
04 net saturday eugene sukhikh ''the basic performance questions''04 net saturday eugene sukhikh ''the basic performance questions''
04 net saturday eugene sukhikh ''the basic performance questions''DneprCiklumEvents
 
04 net saturday eugene sukhikh ''the basic performance questions''
04 net saturday eugene sukhikh ''the basic performance questions''04 net saturday eugene sukhikh ''the basic performance questions''
04 net saturday eugene sukhikh ''the basic performance questions''DneprCiklumEvents
 
06 net saturday eugene zharkov ''silverlight. to oob or not to oob''
06 net saturday eugene zharkov ''silverlight. to oob or not to oob''06 net saturday eugene zharkov ''silverlight. to oob or not to oob''
06 net saturday eugene zharkov ''silverlight. to oob or not to oob''DneprCiklumEvents
 
03 net saturday anton samarskyy ''document oriented databases for the .net pl...
03 net saturday anton samarskyy ''document oriented databases for the .net pl...03 net saturday anton samarskyy ''document oriented databases for the .net pl...
03 net saturday anton samarskyy ''document oriented databases for the .net pl...DneprCiklumEvents
 
02 net saturday roman gomolko ''mvvm in javascript using knockoutjs''
02 net saturday roman gomolko ''mvvm in javascript using knockoutjs''02 net saturday roman gomolko ''mvvm in javascript using knockoutjs''
02 net saturday roman gomolko ''mvvm in javascript using knockoutjs''DneprCiklumEvents
 
01 net saturday alex krakovetskiy ''asp.net scaffolding''
01 net saturday alex  krakovetskiy ''asp.net scaffolding''01 net saturday alex  krakovetskiy ''asp.net scaffolding''
01 net saturday alex krakovetskiy ''asp.net scaffolding''DneprCiklumEvents
 
Sergey Khlopenov tools for_development_cross_platform_mobile_ap
Sergey Khlopenov tools for_development_cross_platform_mobile_apSergey Khlopenov tools for_development_cross_platform_mobile_ap
Sergey Khlopenov tools for_development_cross_platform_mobile_apDneprCiklumEvents
 

Plus de DneprCiklumEvents (11)

Convert estimates to plans (Maxym Mykhalchuk Ciklum)
Convert estimates to plans (Maxym Mykhalchuk Ciklum)Convert estimates to plans (Maxym Mykhalchuk Ciklum)
Convert estimates to plans (Maxym Mykhalchuk Ciklum)
 
Vladimir kozhayev handmade isometry
Vladimir kozhayev handmade isometryVladimir kozhayev handmade isometry
Vladimir kozhayev handmade isometry
 
Pavel yuriychuk svg in game development
Pavel yuriychuk svg in game developmentPavel yuriychuk svg in game development
Pavel yuriychuk svg in game development
 
Vitaly hit' abc_of_game_development
Vitaly hit' abc_of_game_developmentVitaly hit' abc_of_game_development
Vitaly hit' abc_of_game_development
 
04 net saturday eugene sukhikh ''the basic performance questions''
04 net saturday eugene sukhikh ''the basic performance questions''04 net saturday eugene sukhikh ''the basic performance questions''
04 net saturday eugene sukhikh ''the basic performance questions''
 
04 net saturday eugene sukhikh ''the basic performance questions''
04 net saturday eugene sukhikh ''the basic performance questions''04 net saturday eugene sukhikh ''the basic performance questions''
04 net saturday eugene sukhikh ''the basic performance questions''
 
06 net saturday eugene zharkov ''silverlight. to oob or not to oob''
06 net saturday eugene zharkov ''silverlight. to oob or not to oob''06 net saturday eugene zharkov ''silverlight. to oob or not to oob''
06 net saturday eugene zharkov ''silverlight. to oob or not to oob''
 
03 net saturday anton samarskyy ''document oriented databases for the .net pl...
03 net saturday anton samarskyy ''document oriented databases for the .net pl...03 net saturday anton samarskyy ''document oriented databases for the .net pl...
03 net saturday anton samarskyy ''document oriented databases for the .net pl...
 
02 net saturday roman gomolko ''mvvm in javascript using knockoutjs''
02 net saturday roman gomolko ''mvvm in javascript using knockoutjs''02 net saturday roman gomolko ''mvvm in javascript using knockoutjs''
02 net saturday roman gomolko ''mvvm in javascript using knockoutjs''
 
01 net saturday alex krakovetskiy ''asp.net scaffolding''
01 net saturday alex  krakovetskiy ''asp.net scaffolding''01 net saturday alex  krakovetskiy ''asp.net scaffolding''
01 net saturday alex krakovetskiy ''asp.net scaffolding''
 
Sergey Khlopenov tools for_development_cross_platform_mobile_ap
Sergey Khlopenov tools for_development_cross_platform_mobile_apSergey Khlopenov tools for_development_cross_platform_mobile_ap
Sergey Khlopenov tools for_development_cross_platform_mobile_ap
 

Dernier

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 

Dernier (20)

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

Pavel kravchenko obj c runtime

  • 1. Objective-C Runtime Pavel Kravchenko, Ciklum
  • 2. Agenda  What is runtime?  How we can use runtime?  How does it work?  What is object, class, isa, metaclass?  What can we do with runtime?
  • 3. What is it? The runtime system acts as a kind of operating system for the Objective-C language
  • 4. Purpose - understanding basic principles - some useful things (class method, respondsToSelector, etc) → more simple, effective & understandable code - tricks (dynamic loading, change of method implementation, simulation of multiple inheritance)
  • 5. Interacting with Runtime through Objective-C source code through NSObject methods and through direct calls to runtime
  • 8. Basic Types typedef struct objc_selector *SEL; typedef struct objc_class *Class; typedef struct objc_object { Class isa; } *id struct objc_class { Class isa; Class super_class; } struct objc_method { SEL method_name; char *method_types; IMP method_imp; }
  • 11. Messaging  [target method:arg1 :arg2] → objc_msgSend(target, selector, arg1, arg2)  SEL selector = @selector(method::);  SEL is unique identifier of the method name
  • 12. Messaging ■ It first finds the method implementation that the selector refers to. ■ It then calls the procedure, passing it the receiving object, along with any arguments that were specified for the method. ■ Finally, it passes on the return value of the procedure as its own return value.
  • 13. Dynamic Method Resolution void dynamicMethodIMP(id self, SEL _cmd) { // implementation .... } + (BOOL) resolveInstanceMethod:(SEL) aSEL { if (aSEL == @selector(resolveThisMethodDynamically)) { class_addMethod([self class], aSEL, (IMP) dynamicMethodIMP, "v@:"); return YES; } return [super resolveInstanceMethod:aSEL]; }
  • 14. Message Forwarding 2011-03-26 07:32:26.268 First[48403:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSCFString setObject:forKey:]: unrecognized selector sent to instance 0x4e0cc70' *** Call stack at first throw: ( 0 CoreFoundation 0x00db4be9 __exceptionPreprocess + 185 1 libobjc.A.dylib 0x00f095c2 objc_exception_throw + 47 2 CoreFoundation 0x00db66fb -[NSObject(NSObject) doesNotRecognizeSelector:] + 187 3 CoreFoundation 0x00d26366 ___forwarding___ + 966 4 CoreFoundation 0x00d25f22 _CF_forwarding_prep_0 + 50 5 First 0x00002616 -[My1 newM] + 101 6 First 0x00001f00 -[My1 mySelector] + 50
  • 15. Message Forwarding  Sending a message to object that does not handle it is an error  Before error (crash) runtime gives the receiving object second chance to handle wrong message  We need to implement methods of another class, but cannot subclass it
  • 17. Message Forwarding - (void)forwardInvocation:(NSInvocation *) anInvocation { if ([someOtherObject respondsToSelector: [anInvocation selector]]) [anInvocation invokeWithTarget:someOtherObject]; else [super forwardInvocation:anInvocation]; }
  • 18. Message Forwarding @implementation NSObject (NoCrash) - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector { NSMethodSignature *methodSignature = [NSMethodSignature signatureWithObjCTypes:"v@:"]; return methodSignature; } - (void) forwardInvocation:(NSInvocation *)anInvocation { }
  • 19. Tricks id classObj = objc_getClass("SomeClass"); unsigned int outCount, i; objc_property_t *properties = class_copyPropertyList(classObj, &outCount); for (i = 0; i < outCount; i++) { objc_property_t property = properties[i]; NSString *selector = [NSString stringWithCString:property_getName(property)]; SEL selForProperty = NSSelectorFromString(selector); NSLog(@"%@", [self performSelector:selForProperty]); }
  • 20. KVO  Automatic key-value observing is implemented using a technique called isa-swizzling.  What KVO does when you request to observe some property: 1. Gets the class of the object 2. Creates a new subclass of the object's class 3. Overrides the -class method with one that returns the Class of the original class 4. Overrides the desired setter methods in the original class 5. Sets the isa variable of the object to the new subclass
  • 21. Method swizzling DataObject * dataObject = [[DataObject alloc] init]; [dataObject addObserver:self forKeyPath:@"dataValue" options:0 context:NULL]; NSLog(@"%@", [dataObject class]); //logs "DataObject" NSLog(@"%@", object_getClass(dataObject)); //logs "NSKVONotifying_DataObject"
  • 22. Method swizzling Method existingMethod = class_getInstanceMethod([self class], @selector(viewDidLoad)); Method myNewMethod = class_getInstanceMethod([self class], @selector(viewDidLoadMy)); method_exchangeImplementations(existingMethod, myNewMethod); @implementation UIViewController (someCategory) - (void) viewDidLoadMy { [self viewDidLoadMy]; NSLog(@"Print info"); }
  • 23. Links  http://touchdev.ru/documents/958  http://www.sealiesoftware.com/blog/archive/200 9/04/14/objc_explain_Classes_and_metaclasse s.html  http://cocoawithlove.com/2010/01/what-is-meta- class-in-objective-c.html  http://cocoasamurai.blogspot.com/2010/01/und erstanding-objective-c-runtime.html  Objective C Runtime Programming Guide  Objective C Runtime Reference
  • 24. About me  Pavel Kravchenko  skype: ideateam_macuser  email: kravchenkopo@gmail.com  Interests:  iOS, Android, security  Manadgment