when writing interface and implementation files, is there a middle found between choosing one class of objects to use as arguments or to be returned and using id? That is, can I choose a collection of classes that could be used instead of just one specific one or any object type (id)?
2 Answers
You could choose a common superclass, or a protocol if the valid classes all implement a protocol.
Comments
You could specify that the Objective-C type must conform to a protocol. NSObject is both a class and a protocol. So, one idea would be to specify id<NSObject>.
Or, alternatively, have your protocol extend the NSObject protocol. You'll need that if you want use of methods such as respondsToSelector.
4 Comments
chartman
I didn't even realize that I wanted to use respondToSelector until you suggested it and I looked it up.
Max MacLeod
no worries! Yep, it's standard practice to call that before doing performSelector on a delegate
bbum
If you are using a design pattern (outside of @protocol with @optional methods) that requires significant use of
respondsToSelector: or isKindOfClass:, your architecture is likely sub-optimal or, at the least, very much outside the norm. In general, you should very rarely need to use either raw id as a type or use introspection.Max MacLeod
I thought established practice for delegates was to check first with
respondsToSelector: before calling a method. I see it everywhere including in Apple's sample code and documentation. Have I missed something?