This question already has answers here:
Closed 7 years ago.
Possible Duplicate:
Is there any way to enforce typing on NSArray, NSMutableArray, etc.?
I'm Java programmer and I'm starting on Obj-C, in java i can create a mutable array with determined type of class, like as follow:
ArrayList<MyClass> list;
in Obj-c I know the NSMutableArray but i don't know and not found how to determinate the type of class into it.
Have a way of make this with it or other class without NSMutableArray which can do this?
Thanks a lot.
No, Cocoa/Objective-C doesn't offer typed collections like this. All objects in the collection must inherit from NSObject
(which is basically everything besides primitives and structs), but beyond that, it's up to you to understand/manage what is going on in the array. Objects in an NSMutableArray
are represented in its interface by the generic type id
.
From a design standpoint, collections in Cocoa typically do contain homogeneously-typed objects. The name of the array is often used to indicate what's inside it (just as in Java), e.g. bookTitlesArray
or just bookTitles
(i.e. strings). Additionally, from an abstraction standpoint, sometimes lightweight classes are used to "wrap" a raw NSMutableArray
to enforce type checking at the interface. As in, a new class called BookTitleList
which offered a subset of the add, lookup, remove methods and passed them through to an internal array after e.g. validation. But YMMV depending on your needs.
Although there are no type parameters in Objective C, you'll find it much less of a nuisance than in Java because you don't have to downcast to call a method. Objective C is more like JavaScript in this respect.