Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSUserDefaults - Xamarin

I'm just trying to save / restore a couple doubles. What I'm seeing is that it works while attached to debugger, but after 15 minutes of the app being closed - relaunch app and it restores "-180" for both doubles.

Does this look right? Or you think I'm saving "-180" somehow?

This is with device not simulator. i'm using Map.DidUpdateUserLocation which gives MKUserLocationEventArgs.

Somehow it gives -180,-180 for position. Possible Xamarin bug?

    private CLLocationCoordinate2D GetLastLocation()
    {
        var user = NSUserDefaults.StandardUserDefaults;

        double lat = user.DoubleForKey ("LastPositionLat");
        double lng = user.DoubleForKey ("LastPositionLng");

        var location = new CLLocationCoordinate2D (lat, lng);
        return location;
    }

    private void SaveLastLocation(CLLocationCoordinate2D coord)
    {
        var user = NSUserDefaults.StandardUserDefaults;
        user.SetDouble (coord.Latitude, "LastPositionLat");
        user.SetDouble (coord.Longitude, "LastPositionLng");
        user.Synchronize ();
    }
like image 607
Quincy Avatar asked Aug 06 '13 21:08

Quincy


2 Answers

This question is quite old, but it jumped at me for one reason, we've seen very strange behavior storing NSUserDefaults.StandardUserdefaults in a local variable and then repeatedly accessing it.

Something in the Xamarin.iOS binding (at least for the MonoTouch, i.e. non-unified API) is pretty broken there, likely a GC issue where the object looses it's native peer. We have this in our codebase:

    // it appears that capturing an instance of NSUserDefaults.StandardUserdefaults in a variable does not work in every case
    // we have observed a voodoo bug when reading a written value from such an instance would fail (as I said, voodoo!)
    // thus, we directly access standard user defaults here always via the lambda
like image 141
Johannes Rudolph Avatar answered Nov 13 '22 05:11

Johannes Rudolph


Perhaps you could use the nuget package for handling (PCL) Settings that you can find on github here or install through nuget here

I've used this library on many projects in the past, and never presents me with any strange values. Please note that if you do see '-180' appear all over again, it means that something, somewhere in your code is writing that value.

like image 2
Erik J. Avatar answered Nov 13 '22 05:11

Erik J.