I have a managed array of int
s, let's call it int[] intArray
, and I'm trying to create an NSArray
of NSNumber
s from it. What's the easiest way to do that?
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.
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.
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.
Given:
int[] intArray = {1,2,3};
You can do:
NSArray nsArray = NSArray.FromObjects(intArray);
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));
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