Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an `NSArray` out of a managed (C#) array of, say, `int`s?

I have a managed array of ints, let's call it int[] intArray, and I'm trying to create an NSArray of NSNumbers from it. What's the easiest way to do that?

like image 999
sblom Avatar asked Jul 14 '12 20:07

sblom


People also ask

How do I create an NSArray in Objective C?

Creating NSArray Objects Using Array Literals In addition to the provided initializers, such as initWithObjects: , you can create an NSArray object using an array literal. In Objective-C, the compiler generates code that makes an underlying call to the init(objects:count:) method.

What is the difference between array and NSArray?

Array is a struct, therefore it is a value type in Swift. NSArray is an immutable Objective C class, therefore it is a reference type in Swift and it is bridged to Array<AnyObject> . NSMutableArray is the mutable subclass of NSArray . Because foo changes the local value of a and bar changes the reference.

Is NSArray ordered?

In Objective-C, arrays take the form of the NSArray class. An NSArray represents an ordered collection of objects. This distinction of being an ordered collection is what makes NSArray the go-to class that it is.


2 Answers

Given:

int[] intArray = {1,2,3};

You can do:

NSArray nsArray = NSArray.FromObjects(intArray);
like image 158
sblom Avatar answered Sep 30 '22 15:09

sblom


Your answer is the simplest way if the (C#) array values are known at time you create the NSArray instance.

An alternative, if you need to modify (e.g. add more or remove items) the array after the creation, is to create an NSMutableArray and call its Add method to add your own values.

Since you're using int you'll need to call NSObject.FromObject on each integer you have.

int[] intArray = {1,2,3};
var nsArray = new NSMutableArray (3);
foreach (int i in intArray)
   nsArray.Add (NSObject.FromObject (i));
like image 24
poupou Avatar answered Sep 30 '22 14:09

poupou