In Xamarin documentation for Foundation.NSObject
, in Lifecycle section, it says:
C# NSObjects are also created on demand when you invoke a method or a property that returns an NSObject. At this point, the runtime will look into an object cache and determine whether a given Objective-C NSObject has already been surfaced to the managed world or not. If the object has been surfaced, the existing object will be returned, otherwise a constructor that takes an IntPtr as a parameter is invoked to construct the object.
Is there a way to do the above from my code? In other words, given an IntPtr
handle, can I get a C# NSObject
if it already exists or let Xamarin create a new one if it doesn't?
The reason I want to do the above is that I want to keep the IntPtr
handle of a C# NSObject
and then Dispose()
it. Later in the code, I want to get the NSObject
back from that IntPtr
.
The reason I want to do the above is that I've read enough documentation, blogs and SO questions about the interaction between the C# garbage collector and the native refcounted objects in Xamarin.iOS that I decided to Dispose()
everything as soon as possible. So in all methods, I use using
whenever I get an NSObject
argument. For example:
[Foundation.Action("buttonPressed:")]
public void RatingButtonTapped(UIButton button) {
using (button) {
Console.WriteLine("Hello world");
}
}
So if I had kept a reference to the UIButton
earlier during initialization, it will be disposed when this action is run. So instead, I plan to keep the IntPtr
handle instead and re-get the UIButton
when I need it later.