I am used to seeing things like id<NSCopying> myVar or MyObject<NSCopying> myVar, where we are stating that the variable in question can happily have NSCopying methods called on it without the compiler throwing a wobbly.
But I recently spotted some code that defined a variable like this:
Class<NSCopying> myClass;
I was wondering what this actually means as it seems subtly different from the top two examples. It seems like we're saying that the variable myClass can happily accept method calls from NSCopying - but having a class type able to accept these instance variable methods doesn't seem to make much sense.
It has occurred to me that variables of type class are technically objects themselves which is probably confusing me or the compiler (probably me!).
So I guess I'm asking:
- What does something like
Class<NSCopying> myClass;actually mean - How does
Class<NSCopying> myClass;differ to something likeid<NSCopying> myVar - Where could something like
Class<NSCopying> myClass;be meaningfully used?
Notes:
- I am just using
NSCopyingas an example and isn't integral to my use case - Wherever I refer to
ClassI mean the Obj-C keywordClassfor declaring variables that are of typeClass. I am not using this as a generic term for any class type.
Using
idyou can supply an instance of any type of class (so long as it implements the protocol, or you cast it to make the compiler trust you).Using
Classmeans you can only supply aClass, not an instance.Say you wanted your app to be configurable. Say you had a number of classes which offered a number of different features, but you didn't care about inheritance they had, just how to create and configure them. You could use a protocol that the class has to conform to and offer a method where the classes can be registered. Then you can instantiate those classes using the defined protocol without knowing anything else about the class.