Ok, so I have the code below (Objective-C FYI) and I was wondering if I want to create an NSMutableArray of c_data
objects, how would I go about doing that? It\'s s
You would create an NSMutableArray and insert c_data
objects into it.
There is no such thing as statically typed / template / generic collections in Objective-C. Basically, the point of a strongly-typed collection is to provide static type safety at compile time. Such an approach makes little sense in a language as dynamic as Objective-C. The approach to the problem of disparate object types in Objective-C collections is to only insert the appropriate object type(s). (Also, remember that the array will retain objects it contains, so if you insert a new object without releasing and you lose the pointer to it, you're leaking memory.)
If you think about it, one of the biggest benefits to generics is being able to retrieve objects from the collection directly into a statically-typed variable without casting. In Objective-C, you can just store to an id
variable and send whatever message you like without fretting about a ClassCastException, or the compiler complaining that an object doesn't (may not?) implement the method you're attempting to invoke. You can still statically type variables and cast results if desired, but the easier approach is to use dynamic typing (and -isKindOfClass: and -respondsToSelector: if necessary).
Incidentally, there are several related incarnations of this question on Stack Overflow. Knowing the term(s) to search for ("generic", "strongly-typed", or "template") can help find them. Here are a few:
Finally, I agree with William — your init methods are pretty egregious in the sample you provided. You'd do well to learn and heed Apple's rules of Allocating and Initializing Objects in Objective-C. It requires breaking habits from other languages, but it will save you endless hours of insanity at some point down the road. :-)
[NSMutableArray addObject:[[[c_data alloc] init] autorelease]];
Objective-C arrays aren't typed. It seems you have some C++ unlearning to do.
On a related note, your inits are pretty bad. You need to call super init as well, as such:
- (id)init {
self = [super init];
if (self != nil) {
//Initialize here.
}
return self;
}