2

In Java you can use generics to force the use of objects of a certain class.

Example: ArrayList forces the ArrayList to have instances of TestObject in it. This provides a strict list of objects.

I know you can also do this in Actionscript with the Vector class.

Is there any way to do this in Objective-C?

zachzurn
  • 2,161
  • 14
  • 26
  • See this post. This is what you are exactly looking for; http://stackoverflow.com/questions/13751906/does-objective-c-have-an-equivalent-to-java-annotations/13753062#13753062 – Sandeep Feb 01 '13 at 21:44

2 Answers2

3

No, there is no equivalent. The only thing even remotely close is creating your own collection that, at runtime, enforces the class you've picked, but Java generics is a compile-time thing and there's no equivalent in obj-c.

Lily Ballard
  • 182,031
  • 33
  • 381
  • 347
  • Hi, @KevinBallard. Could you please be so kind as to cite a sample code how this can be done in Objective-C? Thanks in advance. – Unheilig May 13 '14 at 18:08
  • @Unheilig: You really shouldn't do this. Any such code would only be able to throw an error at runtime, and that's not very good. But if you really need it, it's straightforward. Just test the class in your `-addObject:` (or equivalent) method. – Lily Ballard May 13 '14 at 18:29
  • Thanks for response. Would you happen to know why there is such a need for Java but not, in Objective-C? – Unheilig May 13 '14 at 18:37
  • 1
    @Unheilig: Java doesn't enforce this at runtime AFAIK. Java Generics are done via type-erasure, which means that all `ArrayList` instances use a single implementation at runtime regardless of what `E` is, and that implementation doesn't have the faintest idea what `E` was. It would be nice if you could do this in obj-c as well, but you can't, and adding runtime type-checking turns what should be a compile-time error into a runtime error, along with a performance cost. – Lily Ballard May 13 '14 at 22:33
1

From iOS 9 there are generics.

I can't find the reference to docs but this article contains a couple of words about the topic:
http://iosdevtips.co/post/121053658888/wwdc-ios-9-swift-2-notes

UPDATE:
There is also a new related feature called KindOf Types.
You can read about this one at the end of the article:
https://medium.com/the-traveled-ios-developers-guide/objective-c-in-2015-3cb7dab3690c

Mikhail
  • 1,061
  • 2
  • 13
  • 30