Violating your classes Objective-C with method swizzling
Went to a iOS programmers meetup recently here in Portland and they did a talk on the C-runtime. I missed most of the talk due to other commitments, but the topic of method swizzling came up.
Basically, it allows you to change what class methods are called by a class – at runtime. In other words, you can start willy-nilly re-pointing your member functions at runtime by:
- Create your 2 or more classes as normal (class A, class B)
- Create some methods off each class you want to swizzle (A.thisFunc, B.thatFunc)
- Swap’em – using the runtime functions:
- class_getInstanceMethod()
- class_addMethod()
- class_replaceMethod()
- method_exchangeImplementations()
- Profit!
While this is obviously very, very dangerous and likely not something you’d do in production, it does create some interesting opportunities for testing and exercising record/replay and persist/restore code.
Either way – interesting write-up. Perhaps the title of the talk should have been called ‘Stupid Objective-C tricks’. 🙂