0

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 2

3

You could choose a common superclass, or a protocol if the valid classes all implement a protocol.

Sign up to request clarification or add additional context in comments.

Comments

1

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

I didn't even realize that I wanted to use respondToSelector until you suggested it and I looked it up.
no worries! Yep, it's standard practice to call that before doing performSelector on a delegate
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.
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?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.