Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using NSArray with Monotouch

How to insert items into NSArray object in C# (Monotouch)? I don't find appropriate method to do so? In Objective-C side, there is a constructor called "initWithObjects" but I don't find this on C# side.

pom

like image 386
Pompair Avatar asked Dec 06 '09 14:12

Pompair


3 Answers

Sorry to answer your question with a question, but are you sure you want to create an NSArray?

I ask because MonoTouch does some work behind the scenes so that you don't have to deal with NSArray.

If you go to the MonoTouch API Design page and do an in-page search for "NSArray", you'll find this:

Instead of dealing with NSString and NSArray the runtime instead exposes these as C# strings and strongly typed arrays throughout the API.

In other words, unless you have a specific reason to, you don't have to mess with NSArray.

But, if you do have a reason, or if it's your preference, then Jason's answer is correct:

NSArray someArray = NSArray.FromNSObjects(thingOne, thingTwo, thingThree);

The only thing I'd add is that, if you're an Objective-C dev and giving MonoTouch a try, you're used to this:

NSArray *someArray = [NSArray arrayWithObjects:obj1, obj2, obj3, nil];

The difference is the "nil" at the end of the Objective-C version. MonoTouch's NSArray doesn't have this same requirement. You just pass it the objects you want it to contain, and it happily does so. No terminating null required :)

Hope this helps...

like image 109
Rory Blyth Avatar answered Oct 07 '22 21:10

Rory Blyth


I'm not using Monotouch - but if you're looking to manipulate an NSArray, you're going to want to use it's cousin, NSMutableArray.

like image 35
Alex C Schaefer Avatar answered Oct 07 '22 20:10

Alex C Schaefer


It looks like this static method is what you want:

public static NSArray FromNSObjects (params NSObject[] items);

Used like this:

NSArray arr = NSArray.FromNSObjects(obj1, obj2, obj3);
like image 32
Jason Avatar answered Oct 07 '22 22:10

Jason