Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 354
TalkingCode Avatar asked Apr 27 '09 14:04

TalkingCode


People also ask

Does Objective C support generics?

Objective-C supports lightweight Generics since 2015, with the Xcode 7.

Can lists be generic?

You can't declare a list of generic types without knowing the generic type at compile time. You can declare a List<Field<int>> or a List<Field<double>> , but there is no other common base type for Field<int> and Field<double> than object .


1 Answers

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.

like image 188
3 revs Avatar answered Oct 13 '22 04:10

3 revs