17

How is it possible to convert an Object instance to NSObject one?

I've created a NSDictionary from

NSDictionary.FromObjectAndKey();

This method wants an NSObject but I have custom object to pass in:

int key = 2341;
var val = new MyClass();
NSDictionary.FromObjectAndKey(val, key); // obviously it does not work!!

How to fix this? Thank you in advance.

Lorenzo B
  • 33,216
  • 24
  • 116
  • 190

3 Answers3

13

You can not convert an arbitrary object into an NSObject. The NSObject.FromObject will try to wrap common data types like numbers, strings, rectangles, points, transforms, and a handful of other .NET types into their equivalent NSObject types.

In your particular example, "MyClass" would have to derive from an NSObject before you could use it in the NSDictionary.

miguel.de.icaza
  • 32,654
  • 6
  • 58
  • 76
10

The easiest solution I could find was to wrap the .Net object in an NSObject, then unwrap as needed.

public class NSObjectWrapper : NSObject
{
    public object Context;

    public NSObjectWrapper (object obj) : base()
    {
        this.Context = obj;
    }

    public static NSObjectWrapper Wrap(object obj)
    {
        return new NSObjectWrapper(obj);
    }
}

Example use:

// wrap
var myNSObj = NSObjectWrapper.Wrap(new MyClass());
// unwrap
var myObj = myNSObj.Context as MyClass;
Former Gaucho
  • 141
  • 1
  • 4
3

This is the way:

NSDictionary.FromObjectAndKey(NSObject.FromObject(val), NSObject.FromObject(key));
Dimitris Tavlikos
  • 8,170
  • 1
  • 27
  • 31
  • Thank you. But seems not working. An exception is thrown : Obj argument cannot be null. It's quite strange beacuse when I print key or val, values are there! – Lorenzo B Apr 14 '11 at 14:47
  • You are right, I just tested that it compiled. It cannot be converted. You must enter keys/values in an NSDictionary that derive from NSObject. The int conversion succeeds. – Dimitris Tavlikos Apr 14 '11 at 15:30