In Objective-C, when retrieving objects from a collection (for example, using -[NSArray objectAtIndex:]), when does the object need to be cast to its original class, and why?
It seems like when calling methods the cast isn’t necessary but it is when using property dot notation. But I don’t understand exactly why this is.
You need to cast it when using dot notation because of a simple thing: otherwise the compiler treats it as a
struct objc_object { Class isa; } *, which hasn’t got the member you want to get. (In fact, to accessisayou need the->-notation anyway.)This is basically because
-[NSArray objectAtIndex:]returnsid, which is defined as:You need to cast it in order to use dot notation, but you don’t need to cast it to send messages to it. My approach: always cast. 🙂