I have a strongly typed collection:
NSMutableArray<SupportClass *> *_items;
Combining two of your comments:
But [the majority of] programming languages known to me allows to have a typed collection with compile time type checks and at the same time being able to put null objects into it. So I'm just looking for a way to do the same with ObjC.
The trouble you are facing is because you are using a recent addition to Objective-C designed to improve inter-working with Swift, and Swift does not allow you to mix in nulls in this way into your "strongly typed collection".
The Swift model is generally to replace the "reference or null" model you are used to with the "non-null reference and optional" model. In Swift a reference to SomeClassType
is non-null, while the type SomeClassType?
is shorthand for Optional<SomeClassType>
. The Optional
type has two cases: .none
and .some(v)
, and Swift allows you to test for .none
by comparing to nil
.
Swift did not invent this model, (like most parts of the language) it is inherited from others, like the many functional languages which are strong users of such tagged unions.
My question is: Which one is the preferred to deal with the issue from the experienced ObjC developer point of view?
Using NSNull
, as you tried. This was the Apple recommended way, the very raison d'être for NSNull
, but dates from before Apple introduced the lightweight generics to help bridge between Obj-C and Swift.
How do you use the "reference or null" model in the post lightweight generics world? You I think know most of the alternatives, they include:
- Don't. Either don't use the strongly typed collections in Obj-C, or use them following the Swift model.
- Use Swift. If you want static strong typing over runtime typing use a language based on it.
- Use a subclass. Override every method/property to throw an illegal use of null exception. Add an
isNull
predicate. Etc.
- Use a distinguished object. Don't like inheritance, then just create a unique instance of your class to act as the null case. Add appropriate methods/properties to support it.
- Build your own
Optional
in Obj-C.
- Break through the paper wall. Lightweight generics really are a paper-thin layer over the standard collections, just break through it if you must.
- Etc.
There is no single "right way" to address your issue. Look at your design, decide whether the "reference of null" model is key, pick a solution that suits your circumstances.
HTH