Crash when dynamic dispatch method For Class Extension Method

This is a low-level implementation detail, but subclasses of NSObject use a different implementation of reference counting from pure Swift classes. That's why you get a crash in the Swift runtime: it's trying to retain a subclass of NSObject using the logic that makes sense for pure Swift objects.

(Strictly speaking, maybe this retain isn't necessary, but I still wouldn't bet on this working in general.)

As an aside, if you're going to use the Objective-C runtime to change method implementations, you should always mark those methods as dynamic. Otherwise, the compiler might try to inline calls to those methods, and you won't get the implementation you're expecting.

1 Like