Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Pavel kravchenko obj c runtime


Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this

Pavel kravchenko obj c runtime

  1. 1. Objective-C Runtime Pavel Kravchenko, Ciklum
  2. 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. 3. What is it?The runtime system acts as a kind of operating system for the Objective-C language
  4. 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. 5. Interacting with Runtimethrough Objective-C source codethrough NSObject methodsand through direct calls to runtime
  6. 6. NSObject methodsclassIsKindOfClass:IsMemberOfClass:RespondsToSelector:ConformsToProtocol:MethodForSelector:
  7. 7. Runtime methodsclass_addMethodclass_replaceMethodobjc_setAssociatedObjectobjc_getAssociatedObjectmethod_setImplementationmethod_exchangeImplementations
  8. 8. Basic Typestypedef struct objc_selector *SEL;typedef struct objc_class *Class;typedef struct objc_object { Class isa;} *idstruct objc_class { Class isa; Class super_class;}struct objc_method { SEL method_name; char *method_types; IMP method_imp;}
  9. 9. Classes andmetaclasses
  10. 10. Messaging
  11. 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. 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. 13. Dynamic Method Resolutionvoid 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. 14. Message Forwarding2011-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 + 1851 libobjc.A.dylib 0x00f095c2 objc_exception_throw + 472 CoreFoundation 0x00db66fb -[NSObject(NSObject) doesNotRecognizeSelector:] + 1873 CoreFoundation 0x00d26366 ___forwarding___ + 9664 CoreFoundation 0x00d25f22 _CF_forwarding_prep_0 + 505 First 0x00002616 -[My1 newM] + 1016 First 0x00001f00 -[My1 mySelector] + 50
  15. 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
  16. 16. Message Forwarding
  17. 17. Message Forwarding- (void)forwardInvocation:(NSInvocation *) anInvocation { if ([someOtherObject respondsToSelector: [anInvocation selector]]) [anInvocation invokeWithTarget:someOtherObject]; else [super forwardInvocation:anInvocation];}
  18. 18. Message Forwarding@implementation NSObject (NoCrash)- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector{ NSMethodSignature *methodSignature = [NSMethodSignature signatureWithObjCTypes:"v@:"]; return methodSignature;}- (void) forwardInvocation:(NSInvocation *)anInvocation{}
  19. 19. Tricksid 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. 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 object2. Creates a new subclass of the objects class3. Overrides the -class method with one that returns the Class of the original class4. Overrides the desired setter methods in the original class5. Sets the isa variable of the object to the new subclass
  21. 21. Method swizzlingDataObject * 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. 22. Method swizzlingMethod 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. 23. Links 9/04/14/objc_explain_Classes_and_metaclasse s.html class-in-objective-c.html erstanding-objective-c-runtime.html Objective C Runtime Programming Guide Objective C Runtime Reference
  24. 24. About me  Pavel Kravchenko  skype: ideateam_macuser  email:  Interests:  iOS, Android, security  Manadgment