Objective-C Properties Problems

Objective-C 2.0 introduced properties as syntactic sugar over getter and setter a very long time back. Properties are very convenient for most of the things but there are quite a few issues that I feel always with them. Today I would like to document them.

Objective-C Subclass Factory Pattern

It’s not an secret that creating instances in Objective-C can be very verbose. It doesn’t help that we don’t have default values and by default everything is initialized to zero. It gets even more verbose when you want to write a robust code and don’t want to expose properties as readwrite where they shouldn’t be. That said, a lot of times keeping them readwrite is better than wiring things around it. Remember that properties in Objective-C, unlike say C++, are just syntactic sugar over getters and setters.

Objective-C safe downcasting

Swift has this nice concept of optional chaining which is used in a lot of places. One really good use case is when down casting a type the operation becomes a no-op if casting to an incorrect sibling. To illustrate take a look at this Swift example code:

Rx with Objective-C using NSInvocation

I want to make a point that NSInvocation is a really powerful tool. If we do not care too much about a compiler type checking every single line of our code we can build a scalable Rx implementation using NSInvocation.

Implementing enum with associated values in Objective-C

Swift has this amazing thing called enum with associated value. Enums are traditionally used to represent a type system with finite set of values. But in real life each of those enum types sometimes have a need to associate some data. And the data of one enum type might be very different than the rest. Imagine writing a parser where each node is of type Node. We usually want to deal with Node as the type for doing things like passing Node around, or generate an array of Node. We might also have methods on Node, such as node.print() but Node can never be instantiated directly as n = Node().