views:

329

answers:

3

Hi,

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

A: 

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);
Jason
That isn't inserting, that's creating WITH objects.
Sneakyness
This was actually what I wanted, I just had formulated my question wrong.
Pompair
Sneakyness: Based on his question, it sounded like he wanted the MonoTouch way to call `initWithObjects`. Pompair: you could mark mine as accepted :)
Jason
+2  A: 

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.

Alex C Schaefer
This also applies to NSDictionary, as there is NSMutableDictionary as well. Just FYI.
Sneakyness
+1  A: 

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...

Rory Blyth
Thank for bringing the internal efforts of MonoTouch to my attention. I didn't know that.
Pompair