New to objective-c. When I write code in strongly-typed OO languages, I like to make my design as explicit as possible in the code, I also like to make sure that I’m maintaining program correctness by checking parameter value ranges, etc (for example, at the beginning of a method make sure that an object reference is not null, use constants as much as possible..). These simple checks, have helped my colleagues and I to catch issues during dev time.
Now working in objective-c, I’m really tempted to check to make sure that a selector is supported before sending a message to a protocol implementation. Or manually check for type compatibility of objects in an NSArray.
Are these types of checks normal in objective-c programs? When do you deem these checks necessary?
Thanks in advance.
What you’re trying to do is totally acceptable, although not necessarily the bread and butter of every programmer’s approach. (I don’t always do this, although perhaps I should.)
The way you’d check would be like so:
If you send a message to an object that it doesn’t respond to, you’ll get a runtime crash. If you check ahead of time, your logic might be totally off. (A common example is when you think you’re dealing with one object, when you are in fact, working with something entirely different. This introduces the tradeoff between crashes during development versus expected values/behavior at runtime.
If you code carefully, you’ll go a lot farther than verbose checking.
Edit:
Thinking about your question a little more, the runtime also offers the
conformsToProtocol:method, which allows you to check if a class or an instance conforms to a protocol. This would seem to be exactly what you want.A place where this is actually essential to not crashing, no matter how careful you are, is when you add support for new iOS features while maintaining backwards compatibility. (In such cases you weak link against new frameworks and use these very same checks to ensure compatibility.
As others have noted, you do get some form of compile-time checking when it comes to protocols. If a method isn’t denoted as
@optional, the Xcode will warn you of an incomplete implementation.