0

I am trying to learn iOS, I come from Java background where we can have lists/arrays of specific classes like

List<String> l = new ArrayList<>();
List<MyClass> l = new ArrayList<>();

Looking at Objective-C, I can make use of NSArray class to make immutable arrays, but how do I specify that this NSArrray is strictly of type MyClass?

daydreamer
  • 73,989
  • 165
  • 410
  • 667

3 Answers3

4

Now Xcode 7 supports some kind of generics for standard collections(e.g. NSArrays). So you can make an array and provide kind of storing objects like this:

NSArray<NSString*> *myArrayOfStrings;
2

As far as I know, there isn't a built-in mechanism for specifying the type of objects put into NSArrays in Objective-C, but it looks like Swift does what you're looking for if that helps at all:

https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html#//apple_ref/doc/uid/TP40014097-CH8-XID_172

On a slightly related note, there's a decent write-up here about enforcing inserting objects of only a certain type into a subclassed NSMutableArray and throwing exceptions if trying to insert the wrong object types:

NSMutableArray - force the array to hold specific object type only

Community
  • 1
  • 1
Mike
  • 9,225
  • 5
  • 32
  • 59
0

Sadly there are no generics in Objective-C.

keeshux
  • 526
  • 2
  • 8
  • 1
    Why? I hate the untyped nature of Objective-C. Swift seems to have introduced them though. – keeshux Sep 02 '14 at 15:48
  • 1
    And I hate generics. You spend much more time trying to work around their limitations than you'd spend debugging the very rare event of having the wrong object in the wrong collection. – Hot Licks Sep 02 '14 at 15:50
  • @HotLicks Just use `` and the problem's gone. – akashivskyy Sep 02 '14 at 15:51
  • For such a basic use-case there are only pros and absolutely no downside to using generics. – keeshux Sep 02 '14 at 15:51
  • 1
    ..and the "event of having the wrong object in the wrong collection" is not rare at all for a dynamically-typed language like Objective-C. – keeshux Sep 02 '14 at 15:55
  • I can't remember the last time that I had an instance of the wrong class in an NSArray that was supposed to contain instances of one class only, so I'd say it's rare, once you are past the beginner stage. – gnasher729 Sep 02 '14 at 17:28
  • @gnasher729 bugs happen at any stage and if a language feature can avoid a trivial bug at compile-time I'm happy enough. After all many features are not intrinsically bad until someone uses them the wrong way, generics/templates can be evil but I don't think they are wrong by nature. – keeshux Sep 02 '14 at 17:54