-3
function b(
  a                  // placeholder
){
  return a           // if the placeholder was passed, return
    ? (              // a random number from 0 to 15
      a ^            // unless b is 8,
      Math.random()  // in which case
      * 16           // a random number from
      >> a/4         // 8 to 11
      ).toString(16) // in hexadecimal
    : (              // or otherwise a concatenated string:
      [1e7] +        // 10000000 +
      -1e3 +         // -1000 +
      -4e3 +         // -4000 +
      -8e3 +         // -80000000 +
      -1e11          // -100000000000,
      ).replace(     // replacing
        /[018]/g,    // zeroes, ones, and eights with
        b            // random hex digits
      )
}

Edit: Using the selected answer is the best way, please ignore this question. I'm writing this to appeal to Stack Overflows character limit...

Cole Roberts
  • 954
  • 3
  • 15
  • 25
  • What do you mean by "use this same function"? Do you want to _call_ JS code from ObjC, _rewrite_ the function into ObjC, or _find an equivalent_ in the Cocoa framework? – jscs Mar 13 '16 at 21:49
  • @JoshCaswell I'd like to rewrite the function in ObjC. I'll update the question. – Cole Roberts Mar 13 '16 at 21:50
  • SO is _not_ a rewrite my code plz service. – Bryan Chen Mar 13 '16 at 21:55
  • SO is not a rewrite my code service and calling BryanChen an ass just got you a down vote and a moderator flag. – matt Mar 13 '16 at 21:58

2 Answers2

26

The easiest way to get a UUID in Obj-C is to use the UUID class:

NSUUID *uuid = [NSUUID UUID];
NSString *str = [uuid UUIDString];
EricS
  • 9,650
  • 2
  • 38
  • 34
  • Any idea how I could recreate the exact function above though? I appreciate it. – Cole Roberts Mar 13 '16 at 21:49
  • @ColeRoberts `NSUUID` conform to RFC 4122 version 4 and are created with random bytes and that would be a different question. You should either make a new thread or edit current question. – Cai Mar 13 '16 at 22:04
  • My Javascript isn't quite good enough to translate it verbatim. Sorry. – EricS Mar 14 '16 at 00:08
2

Do it the following way. You can add it as utility API-

+ (NSString *)uniqueIdForObject
{
 CFUUIDRef uniqueString = CFUUIDCreate(NULL);
 CFStringRef isString = CFUUIDCreateString(NULL, uniqueString);
 CFRelease(uniqueString);
 return (NSString *) isString;
}
Avi
  • 2,196
  • 18
  • 18