Method swizzling is the process of changing the implementation of an existing selector. It's a technique made possible by the fact that method invocations in Objective-C can be changed at runtime, by changing how selectors are mapped to underlying functions in a class's dispatch table.
3. What ?
- Replacing the implementation
- Overriding default behaviour
- Dynamic method
- Changing the mapping between a specific
#selector(method)
Swizzling(1/8)
4. How to use ?
+ (void)load
- Notify when the class is initially loaded
+ (void)initialize
- Notify before the application calls its first
method on that class or an instance
+ dispatch_once
- swizzling changes global state
- code will be executed exactly once
Swizzling(2/8)
5. How to use ?
+ Selectors, Methods, & Implementations
- Selector (typedef struct objc_selector *SEL):
represent the name of a method at runtime,
selector is a C string that has been registered (or
“mapped”),
selectors generated by the compiler are automatically
mapped
- Method (typedef struct objc_method *Method):
represents a method in a class definition
Swizzling(3/8)
6. How to use ?
+ Selectors, Methods, & Implementations
- Implementation (typedef id (*IMP)(id, SEL, …)):
a pointer to the start of the function that implements the
method,
first argument is a pointer to self,
second argument is the method selector
Swizzling(4/8)
7. Example
- Using selector & Implementations
+ (void)load
{
Method origMethod = class_getInstanceMethod(self,
@selector(drawTextInRect:));
origDrawTextInRect = (void *)method_getImplementation(origMethod);
if (!class_addMethod(self, @selector(drawTextInRect:),
(IMP)newDrawTextInRect, method_getTypeEncoding(origMethod)))
method_setImplementation(origMethod, (IMP)newDrawTextInRect);
}
Swizzling(5/8)
8. Example
- Using selector
+ (void)load
{
Method original, swizzle;
original = class_getInstanceMethod(self, @selector(initWithFrame:));
swizzle = class_getInstanceMethod(self, @selector(swizzled_initWithFrame:));
// Swap their implementations.
method_exchangeImplementations(original, swizzle);
}
Swizzling(6/8)
10. Dangers of Method Swizzling
- Changes behaviour of un-owned code
- Possible naming conflicts
- Swizzling changes the method's arguments
- The order of swizzles
- Difficult to debug
Swizzling(8/8)
11. How?
- Method Swizzling
- Optimizely downloads a JSON data file
containing all experiment data
- An experiment conflicts with another when
you modify the same view, Live Variable, or
Code Block in multiple experiments.
Optimizely(1/3)
12. How?
- Disabled : the experiment has been paused
from the Optimizely dashboard
- Running: This means the experiment is
running and ready to be viewed.
- Deactivated: This means the experiment
failed a condition required to run
Optimizely(2/3)