Search code examples
iosswiftobjective-ciphone-privateapi

How to set delegate for a private API in Swift or Objective-C?


I can call a private API's method by getClassFromString: and performSelector: in Objective-C, or use the Dynamic library to call them easily in Swift. However, I can't set a delegate for a private API because I can't get a protocol dynamically and make a class conform it.

I've tried to copy the procotol's define and make a class conform it, then used [/*id*/ performSelector:NSSelectorFromString(@"setDelegate") withObject:[[MyDelegate alloc] init]]; in Objective-C. But it seems no effect.


Solution

  • Objective-C doesn't really care if the object that gets set as delegate actually conforms to the protocol. If it doesn't, there will be a run-time crash, but as long as your class implements the protocol methods correctly, you can assign it as a delegate.

    What is most likely happening with your code is that the private class' delegate is declared weak and since nothing else is retaining it, it is immediately deallocated.

    If you keep a strong reference to MyDelegate, then assign that to the private class, it will likely work.