Is there anything like a generic list in Cocoa / Objective-C?

TalkingCode picture TalkingCode · Apr 27, 2009 · Viewed 28.6k times · Source

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.

Answer

Mike Abdullah picture Mike Abdullah · Apr 27, 2009

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.