My question may seem strange, but i wanna to get this idea around Stackers’ minds, in my work i just noticed that every protocol is conformed by a class all the time, i wondered about the possibility to make a simple object conforms to protocols too, and if not (and almost not ), why not ??
Appreciate your concern
There are two parts to protocol conformance:
YESwhen asked whether it conforms to the protocolSo, can we arrange for an instance of
NSObjectto satisfy those two conditions? Yes. In fact, there are at least two ways to do so. First, let’s make all instances ofNSObjectconform to the protocol. What we do is to define the protocol methods in a category onNSObject, which solves the first part. Then we “swizzle” (which means using theclass_replaceMethod()runtime function)-[NSObject conformsToProtocol:], returningYESfor our interesting protocol.Now let’s imagine that you want to make a specific instance of
NSObjectconform to the protocol. This is slightly easier. First, create a subclass ofNSObjectthat conforms to the protocol and implements the required methods; there’s no need to override-conformsToProtocol:because the runtime library can see that this class conforms. Now, at runtime, take yourNSObjectinstance and callobject_setClass()to switch its class to your conforming subclass.