Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set values for NSDictionary<NSString, NSObject> object in Xamarin?

I need to interface with a function that receives an object of type NSDictionary<NSString, NSObject> in Xamarin.

First, I don't understand the syntax. What exactly is a NSDictionary<NSString, NSObject> type object? I know there is NSDictionary type and I know how to create one and set keys and values, but what is NSDictionary<?,?> ? Is it suppose to be some sort of a special tuple?

Second, how do I create such an object and define the key and associated object?

like image 871
Shay Ohayon Avatar asked Sep 24 '16 13:09

Shay Ohayon


2 Answers

NSDictionary<TKey, TValue> is just a generic version of NSDictionary. This means that the keys are all of the type TKey (in your case NSString) and the values are all of type TValue (in your case NSObject.). This provides more type safety, because e.g. you can't add integers as keys. The underlying iOS object is still a NSDictionary. This class is kind of "syntactic sugar", because we are used to strict typing in C# and want to use it where ever possible.

You can create it with a constructor. It has multiple constructors. E.g. NSDictionary(TKey[] keys, TValue[] values) is taking the keys and values as parameters and creates NSDictionary of it.

var keys = new[]
{
    new NSString("key1"),
    new NSString("key2"),
    new NSString("key3"),
    new NSString("key4")
};

var objects = new NSObject[]
{
    // don't have to be strings... can be any NSObject.
    new NSString("object1"),
    new NSString("object1"),
    new NSString("object1"),
    new NSString("object1")
};

var dicionary = new NSDictionary<NSString, NSObject>(keys, objects);
like image 75
Sven-Michael Stübe Avatar answered Sep 19 '22 15:09

Sven-Michael Stübe


On Xamarin.Mac, and following Sven-Michael Stübe, it can be:

var dictionary = new NSDictionary(
    new NSString("key1"), new NSString("object1"),
    new NSString("key2"), new NSString("object2")
);

Probably Xamarin.iOS too but I didn't tested.

like image 24
Karl Heinz Brehme Arredondo Avatar answered Sep 19 '22 15:09

Karl Heinz Brehme Arredondo