Violating your classes Objective-C with method swizzling

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:

  1. Create your 2 or more classes as normal (class A, class B)
  2. Create some methods off each class you want to swizzle (A.thisFunc, B.thatFunc)
  3. Swap’em – using the runtime functions:
    1. class_getInstanceMethod()
    2. class_addMethod()
    3. class_replaceMethod()
    4. method_exchangeImplementations()
  4. 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’. 🙂

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.