Question

I'm reading this book, and it's going over static typing, which, after reading the chapter a little bit, I understand as:

  • Static typing in OOP is defined as explicitly declaring the class an object is an instance of, so that it is predetermined (at compile time, before runtime i.e. Foo var).
  • The opposite of this is generic programming, where the actual id of the object is yet-to-be-determined (i.e. id var).
  • Something to keep in mind is that static typing is never necessary (straight from the book), it only improves readability, and eases the debugging process by showing what an object can and cannot do, what it can “see”.
  • Generic programming, however, is sometimes necessary for things like arrays, where you might need...And this is where I'm confused. Is it actually necessary?

I know that in Java you can enforce the type of objects contained in an array like: ArrayList<Double>, but in Objective-C, and I've done minimal research on this, there is no such method, and therefore, all NSArrays contain ids at compile time.

If this feature (strangely called generics, even though it's static typing and not generic typing), is unavailable in Objective-C, does that mean that generic programming is sometimes necessary?

Was it helpful?

Solution

Yes, generic typing is necessary whenever you need to write something that needs to operate on a number of types without knowing the type at compile time.

While objective-C doesn't contain generics per-se, Ids and void* are basically the same thing. You can write a method that takes in a void* or Id and do some processing on it. Before calling the method, you would do an explicit cast to a void* on the object you want to operate on.

Edit: For instance, what would you do if you wanted to write a method which makes a shallow copy of any typed object? You'd have to do something like copy(void* src,void* dest, int size). There is no way to do this without generics.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top