Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate and store a unique id in MonoTouch

I am looking at transitioning an app of mine from standard iOS Objective C to C# using MonoTouch.

In my Objective C code I am generating a unique identifier and saving it to NSUserDefaults to validate and check on subsequent logins. Here is the method that I am using for that:

- (NSString *) localUuid {
        NSString * ident = [[NSUserDefaults standardUserDefaults] objectForKey:UUID];
        if(!ident){
            CFUUIDRef uuidRef = CFUUIDCreate(NULL);
            CFStringRef uuidStringRef = CFUUIDCreateString(NULL, uuidRef);
            CFRelease(uuidRef);
            ident = [NSString stringWithString:(__bridge_transfer NSString *)uuidStringRef];
            [[NSUserDefaults standardUserDefaults] setObject:ident forKey:UUID];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
        return ident;

    }

I am having problems getting something similar to work in C# with MonoTouch though.

I haven't found a version of the CFUUID__ methods available with Mono.
Also, while there appears to be a NSUserDefaults.StandardUserDefaults.SetValueForKey method, there isn't a straightforward GetValueForKey method.

Does anyone more experienced with Monotouch know a better way to do this?

like image 567
cain Avatar asked Dec 27 '22 13:12

cain


1 Answers

CFUUID is not bound because it's easier to use .NET System.Guid to achieve the same. E.g.

var uuid = Guid.NewGuid ();
string s = uuid.ToString (); // if a string is preferred

Also, while there appears to be a NSUserDefaults.StandardUserDefaults.SetValueForKey method, there isn't a straightforward GetValueForKey method.

There are safely type methods to do the same, e.g.:

NSUserDefaults settings = NSUserDefaults.StandardUserDefaults;
settings.SetString (s, "key");
like image 72
poupou Avatar answered Jan 09 '23 11:01

poupou