The Dark Side
of Objective-C
Martin Kiss | kish | @Tricertops PixelCut s. r. o.
Objective-C Runtime

Creates illusion of objects and messages
@interface
@implementation
[self bracketSyntax]
@property (strong)
self.dotSyntax
@selector()
- (void)methodDeclarations:(id)weird
The Light Side
The Dark Side
objc_allocateClassPair()
class_copyMethodList()
objc_msgSend()
class_getProperty()
class_copyIvarList()
sel_registerName()
method_setImplementation()
What is Runtime?
• C support library

• Manages classes and methods

• Handles method invocations

• Memory management routines

• Manages lifetime of weak references
Why should Swift care?
• Swift is a new syntax for Objective-C

• Frameworks are all in Objective-C

• NSObject and @objc

• Many of things are not possible, yet

• Swift will need its own runtime
What needs runtime?
• NSCoding

• Storyboards & XIBs

• Key-Value Coding

• Key-Value Observing

• Core Animation

• Testing & Mocking
• Core Data

• NSProxy

• UIAppearance

• NSUndoManager

• Cocoa Bindings

• UIResponder
#import <objc/runtime.h>
#import <objc/message.h>
Simple Runtime
Services
Look up Class by Name
High Level
Low Level

How It Works

Used By
NSClassFromString()
objc_getClass()

objc_lookUpClass()
Runtime holds a table of all classes by
their names as keys

NSCoding, Storyboards, XIBs
Perform Selector by Name
High Level

Low Level

How It Works

Used By

NSSelectorFromString()

-performSelector:
sel_registerName()

objc_msgSend()
Classes store method implementations
in tables by selectors as keys

Key-Value Coding, Storyboards, XIBs,
UIControl, UIGestureRecognizer
Store Associated Objects
Functions

How It Works

What Is It For







Used By

objc_getAssociatedObject()

objc_setAssociatedObject()
Runtime holds side-table for each object
until it deallocates

Adding storage to objects without
adding ivars, for example rarely used
values

UIViews, Auto Layout, UIAppearance,
many more
Advanced Runtime
Services
Access Ivars by Name
Functions

How It Works



Used By
class_getInstanceVariable()

class_setInstanceVariable()
Instance variables are accessed
indirectly and classes contain lookup
table

Key-Value Coding, Key-Value Observing
Access Attributes of Properties
Functions

How It Works

What Is It For





Used By
class_getProperty()

property_getAttributes()
Classes include all info about properties,
like name, attributes, and backing ivar

Check if property is weak or strong or if
the property has ivar

Custom CALayer animatable properties
Enumerate Ivars & Properties
Functions

How It Works

What Is It For



Used By

class_copyIvarList()

class_copyPropertyList()
Classes include tables and metadata for
ivars and properties

Inspection of object contents

CALayer animatable properties, Core
Image Filters, automatic descriptions
Enumerate Methods
Function
How It Works

What Is It For



Used By
class_copyMethodList()
Classes include table of methods with
their selectors and implementations

Find methods that match a pattern

Tests & Mocks, UIAppearance
Enumerate Classes
Functions

How It Works

What Is It For

objc_copyClassList()

objc_copyClassNamesForImage()
Runtime holds table of all classes
loaded in your process, per executable

Find classes that match a pattern, find
all subclasses of a class
⚠
Warning: Accessing framework classes will trigger side effects!
Sending Messages
Function
Related

How It Works

What Is It For

objc_msgSend()
-methodForSelector:

-methodSignatureForSelector:
All [bracket calls] are translated to
objc_msgSend()

Perform selectors when standard method

-performSelector: is not enough
⚠
Warning: Requires casting to work properly!
Sending Messages

How it works?
- (void)updateTitle:(NSString *)title {
title = title.trimmedString;

self.title = title;

self.navigationBar.title = title;

}
Sending Messages

Components of a method
updateTitle: void, id, SEL, NSString *
{
title = title.trimmedString;

self.title = title;

self.navigationBar.title = title;

}
Selector Type Signature
Implementation
Sending Messages

Components of a method
updateTitle: void, id, SEL, id
void func(id self, SEL _cmd, id title) {
title = title.trimmedString;

self.title = title;

self.navigationBar.title = title;

}
SEL
IMP
"v@:@"
Sending Messages
[object updateTitle:@"Hello"];
let message = void(*)(id,SEL,id)&objc_msgSend;
SEL selector = @selector(updateTitle:);
message(object, selector, @"Hello");
=
Expert Runtime
Services
learn t|he powER
of t|he dark Side!
Runtime is mutable
Add Methods to Classes
Function
Override

What Is It For

Used By

class_addMethod()
+resolveInstanceMethod:

+resolveClassMethod:
Implement methods on demand, for
example getters of @dynamic properties

Core Data, CALayer animatable
properties, UIAppearance, KVO
Replace Implementations
Functions



Override
What Is It For

Used By

class_replaceMethod()

method_setImplementation()

method_exchangeImplementations()
+load in categories

Extend existing framework classes with

new behaviors

UIAppearance, Key-Value Observing,

Mocking frameworks
⚠
Warning: It is not trivial to implement method swizzling properly!
Forward Invocations
Override



How It Works

What Is It For



Used By
-forwardInvocation:
Unrecognized selectors are passed into
this method before they throw exception

Simulate multiple inheritance, forward
methods to internal components, modify
arguments

NSProxy subclasses, NSUndoManager
Change Class of Object
Functions



How It Works

What Is It For

Used By
object_setClass()
Object has ivar isa, which points to the
class and is used for method lookup

Extend behavior of a single object, not
all objects of that class

Key-Value Observing, Core Data
⚠
Warning: New class should handle all methods of original class!
Create New Classes
Functions





How It Works

What Is It For

Used By
objc_allocateClassPair()

objc_registerClassPair()
Allocate, add methods, ivars, properties,
and then register in runtime

Customize class methods or for using
with object_setClass()

Key-Value Observing, Core Data
self
MyClass
lookup
message
What is Metaclass?

Implementations are looked up in class
Instance Methods
self
MyClass
MyMetaClass
lookup
lookup
message
message
Instance Methods
Class Methods
What is Metaclass?

Class is also an object, so it has a class
self
MyClass
MyMetaClass
lookup
lookup
message
message
Instance Methods
Class Methods
NSObject
message
lookup
How much is it used?

Measured using symbolic breakpoints
Minimal Swift App
import UIKit~~~~~~~~~~~~~~~
@UIApplicationMain~~~~~~~~~~~~~~~

class AppDelegate: NSObject,~~~~~~~~~~~~~~~

UIApplicationDelegate {}
• Initializes UIApplication & Main Run Loop

• No launch Storyboard or XIB
Minimal Swift App
Look up Class 608×
Look up Selector 718×
Get / Set Associated Object 254× / 179×
Copy Method List 378×
Add / Change Method 13× / 1×
Create Class 13×
iOS Dash App
• Documentation viewer

• Standard UI components

• UIKit & WebKit

• 20k LOC of Objective-C
iOS Dash App
Look up Class 1357×
Look up Selector 1283×
Get / Set Associated Object 2803× / 1317×
Copy Method List 515×
Add / Change Method 87× / 14×
Create Class 18×
iOS Kickstarter App
• Crowdfunding app

• Customized UI

• 120k LOC of mixed code
iOS Kickstarter App
Look up Class 2813×
Look up Selector 1455×
Get / Set Associated Object 4375× / 1966×
Copy Method List 496×
Add / Change Method 190× / 10×
Create Class 20×
PaintCode
• Vector drawing Mac app

• Custom complex UI

• 300k LOC of Objective-C

• XIBs with Cocoa Bindings
PaintCode
Look up Class 41189×
Look up Selector 9615×
Get / Set Associated Object 45230× / 2045×
Copy Method List 370×
Add / Change Method 664× / 1×
Create Class 112×
Ask me anything
Thank You
Martin Kiss | kish | @Tricertops PixelCut s. r. o.

The Dark Side of Objective-C

  • 1.
    The Dark Side ofObjective-C Martin Kiss | kish | @Tricertops PixelCut s. r. o.
  • 2.
    Objective-C Runtime Creates illusionof objects and messages
  • 3.
  • 4.
  • 5.
    What is Runtime? •C support library • Manages classes and methods • Handles method invocations • Memory management routines • Manages lifetime of weak references
  • 6.
    Why should Swiftcare? • Swift is a new syntax for Objective-C • Frameworks are all in Objective-C • NSObject and @objc • Many of things are not possible, yet • Swift will need its own runtime
  • 7.
    What needs runtime? •NSCoding • Storyboards & XIBs • Key-Value Coding • Key-Value Observing • Core Animation • Testing & Mocking • Core Data • NSProxy • UIAppearance • NSUndoManager • Cocoa Bindings • UIResponder
  • 8.
  • 9.
  • 10.
    Look up Classby Name High Level Low Level
 How It Works
 Used By NSClassFromString() objc_getClass()
 objc_lookUpClass() Runtime holds a table of all classes by their names as keys NSCoding, Storyboards, XIBs
  • 11.
    Perform Selector byName High Level
 Low Level
 How It Works
 Used By
 NSSelectorFromString()
 -performSelector: sel_registerName()
 objc_msgSend() Classes store method implementations in tables by selectors as keys Key-Value Coding, Storyboards, XIBs, UIControl, UIGestureRecognizer
  • 12.
    Store Associated Objects Functions
 HowIt Works
 What Is It For
 
 
 
 Used By
 objc_getAssociatedObject()
 objc_setAssociatedObject() Runtime holds side-table for each object until it deallocates Adding storage to objects without adding ivars, for example rarely used values UIViews, Auto Layout, UIAppearance, many more
  • 13.
  • 14.
    Access Ivars byName Functions
 How It Works
 
 Used By class_getInstanceVariable()
 class_setInstanceVariable() Instance variables are accessed indirectly and classes contain lookup table Key-Value Coding, Key-Value Observing
  • 15.
    Access Attributes ofProperties Functions
 How It Works
 What Is It For
 
 
 Used By class_getProperty()
 property_getAttributes() Classes include all info about properties, like name, attributes, and backing ivar Check if property is weak or strong or if the property has ivar Custom CALayer animatable properties
  • 16.
    Enumerate Ivars &Properties Functions
 How It Works
 What Is It For
 
 Used By
 class_copyIvarList()
 class_copyPropertyList() Classes include tables and metadata for ivars and properties Inspection of object contents CALayer animatable properties, Core Image Filters, automatic descriptions
  • 17.
    Enumerate Methods Function How ItWorks
 What Is It For
 
 Used By class_copyMethodList() Classes include table of methods with their selectors and implementations Find methods that match a pattern Tests & Mocks, UIAppearance
  • 18.
    Enumerate Classes Functions
 How ItWorks
 What Is It For
 objc_copyClassList()
 objc_copyClassNamesForImage() Runtime holds table of all classes loaded in your process, per executable Find classes that match a pattern, find all subclasses of a class ⚠ Warning: Accessing framework classes will trigger side effects!
  • 19.
    Sending Messages Function Related
 How ItWorks
 What Is It For
 objc_msgSend() -methodForSelector:
 -methodSignatureForSelector: All [bracket calls] are translated to objc_msgSend() Perform selectors when standard method
 -performSelector: is not enough ⚠ Warning: Requires casting to work properly!
  • 20.
    Sending Messages How itworks? - (void)updateTitle:(NSString *)title { title = title.trimmedString;
 self.title = title;
 self.navigationBar.title = title;
 }
  • 21.
    Sending Messages Components ofa method updateTitle: void, id, SEL, NSString * { title = title.trimmedString;
 self.title = title;
 self.navigationBar.title = title;
 }
  • 22.
    Selector Type Signature Implementation SendingMessages Components of a method updateTitle: void, id, SEL, id void func(id self, SEL _cmd, id title) { title = title.trimmedString;
 self.title = title;
 self.navigationBar.title = title;
 } SEL IMP "v@:@"
  • 23.
    Sending Messages [object updateTitle:@"Hello"]; letmessage = void(*)(id,SEL,id)&objc_msgSend; SEL selector = @selector(updateTitle:); message(object, selector, @"Hello"); =
  • 24.
    Expert Runtime Services learn t|hepowER of t|he dark Side!
  • 25.
  • 26.
    Add Methods toClasses Function Override
 What Is It For
 Used By
 class_addMethod() +resolveInstanceMethod:
 +resolveClassMethod: Implement methods on demand, for example getters of @dynamic properties Core Data, CALayer animatable properties, UIAppearance, KVO
  • 27.
    Replace Implementations Functions
 
 Override What IsIt For
 Used By
 class_replaceMethod()
 method_setImplementation()
 method_exchangeImplementations() +load in categories Extend existing framework classes with
 new behaviors UIAppearance, Key-Value Observing,
 Mocking frameworks ⚠ Warning: It is not trivial to implement method swizzling properly!
  • 28.
    Forward Invocations Override
 
 How ItWorks
 What Is It For
 
 Used By -forwardInvocation: Unrecognized selectors are passed into this method before they throw exception Simulate multiple inheritance, forward methods to internal components, modify arguments NSProxy subclasses, NSUndoManager
  • 29.
    Change Class ofObject Functions
 
 How It Works
 What Is It For
 Used By object_setClass() Object has ivar isa, which points to the class and is used for method lookup Extend behavior of a single object, not all objects of that class Key-Value Observing, Core Data ⚠ Warning: New class should handle all methods of original class!
  • 30.
    Create New Classes Functions
 
 
 HowIt Works
 What Is It For
 Used By objc_allocateClassPair()
 objc_registerClassPair() Allocate, add methods, ivars, properties, and then register in runtime Customize class methods or for using with object_setClass() Key-Value Observing, Core Data
  • 31.
  • 32.
  • 33.
  • 34.
    How much isit used? Measured using symbolic breakpoints
  • 35.
    Minimal Swift App importUIKit~~~~~~~~~~~~~~~ @UIApplicationMain~~~~~~~~~~~~~~~
 class AppDelegate: NSObject,~~~~~~~~~~~~~~~
 UIApplicationDelegate {} • Initializes UIApplication & Main Run Loop • No launch Storyboard or XIB
  • 36.
    Minimal Swift App Lookup Class 608× Look up Selector 718× Get / Set Associated Object 254× / 179× Copy Method List 378× Add / Change Method 13× / 1× Create Class 13×
  • 37.
    iOS Dash App •Documentation viewer • Standard UI components • UIKit & WebKit • 20k LOC of Objective-C
  • 38.
    iOS Dash App Lookup Class 1357× Look up Selector 1283× Get / Set Associated Object 2803× / 1317× Copy Method List 515× Add / Change Method 87× / 14× Create Class 18×
  • 39.
    iOS Kickstarter App •Crowdfunding app • Customized UI • 120k LOC of mixed code
  • 40.
    iOS Kickstarter App Lookup Class 2813× Look up Selector 1455× Get / Set Associated Object 4375× / 1966× Copy Method List 496× Add / Change Method 190× / 10× Create Class 20×
  • 41.
    PaintCode • Vector drawingMac app • Custom complex UI • 300k LOC of Objective-C • XIBs with Cocoa Bindings
  • 42.
    PaintCode Look up Class41189× Look up Selector 9615× Get / Set Associated Object 45230× / 2045× Copy Method List 370× Add / Change Method 664× / 1× Create Class 112×
  • 43.
    Ask me anything ThankYou Martin Kiss | kish | @Tricertops PixelCut s. r. o.