Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to enforce typing on NSArray, NSMutableArray, etc.?

Can I make a NSMutableArray instance where all the elements are of type SomeClass?

like image 490
Sam Lee Avatar asked Mar 16 '09 06:03

Sam Lee


People also ask

What's a difference between NSArray and NSSet?

The main difference is that NSArray is for an ordered collection and NSSet is for an unordered collection. There are several articles out there that talk about the difference in speed between the two, like this one. If you're iterating through an unordered collection, NSSet is great.

Can NSArray contain nil?

arrays can't contain nil.

Is NSArray ordered?

An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.

How do you reverse an NSArray?

You can reverse a NSArray by writing your own loop iterating from the end towards the beginning and using a second array to add the items in reverse order. Or you can simply use - (NSEnumerator *)reverseObjectEnumerator from the NSArray class.


1 Answers

Nobody's put this up here yet, so I'll do it!

Tthis is now officially supported in Objective-C. As of Xcode 7, you can use the following syntax:

NSArray<MyClass *> *myArray = @[[MyClass new], [MyClass new]]; 

Note

It's important to note that these are compiler warnings only and you can technically still insert any object into your array. There are scripts available that turn all warnings into errors which would prevent building.

like image 149
Logan Avatar answered Oct 08 '22 20:10

Logan