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.
Objective-C supports lightweight Generics since 2015, with the Xcode 7.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With