What I really like in C# are generic lists. A list that can contain only one type of objects.
Is there something like a generic list in Cocoa/Objective-C? As far I only know NSArray
who will take a pointer to any object.
Wanting this in a Cocoa app is often a sign of a weak design.
NSArray
is immutable, so it will not "take a pointer to any object" and presumably already contains the correct objects when handed to you. What I assume you're more worried about is an NSMutableArray
where you think other parts of your code might add the wrong sort of object. But have a look at Cocoa itself; it's incredibly rare to expose a mutable array as part of a class's design.
Instead, you generally expose an NSArray
and a couple of methods for modifying that array. Something along the lines of:
@class Foo : NSObject
- (NSArray *)bars;
- (void)addBar:(Bar *)bar;
- (void)removeBar:(Bar *)bar;
@end
This generally stops wrong objects being inserted simply by having a compiler warning, and then of course you can add assertions within -addBar:
and -removeBar:
if you wish too.