5

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

3 Answers 3

5

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

1
  • Thank for bringing the internal efforts of MonoTouch to my attention. I didn't know that.
    – Pompair
    Dec 12, 2009 at 10:40
2

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.

1
  • 1
    This also applies to NSDictionary, as there is NSMutableDictionary as well. Just FYI.
    – Sneakyness
    Dec 12, 2009 at 4:25
1

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);
3
  • That isn't inserting, that's creating WITH objects.
    – Sneakyness
    Dec 12, 2009 at 4:24
  • This was actually what I wanted, I just had formulated my question wrong.
    – Pompair
    Dec 12, 2009 at 10:39
  • Sneakyness: Based on his question, it sounded like he wanted the MonoTouch way to call initWithObjects. Pompair: you could mark mine as accepted :)
    – Jason
    Dec 12, 2009 at 15:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.