How to compare NSUUID
Asked Answered
B

4

9

What is the best (least code, fastest, most reliable) way to compare two NSUUIDs?

Here is an example:

-(BOOL)isUUID:(NSUUID*)uuid1 equalToUUID:(NSUUID*)uuid2
{
    return ... // YES if same or NO if not same
}
Bodywork answered 11/12, 2013 at 17:23 Comment(0)
P
13

From the NSUUID class reference:

Note: The NSUUID class is not toll-free bridged with CoreFoundation’s CFUUIDRef. Use UUID strings to convert between CFUUID and NSUUID, if needed. Two NSUUID objects are not guaranteed to be comparable by pointer value (as CFUUIDRef is); use isEqual: to compare two NSUUID instances.

So just use the following:

-(BOOL)isUUID:(NSUUID*)uuid1 equalToUUID:(NSUUID*)uuid2
{
    return [uuid1 isEqual:uuid2];
}
Pulchia answered 11/12, 2013 at 17:31 Comment(1)
Is the comparison necessary as [nil isEqual:uuid2] would also return NO, correct?Bodywork
D
8

You don't need to create an extra method for this, as the documentation states that

NSUUID objects are not guaranteed to be comparable by pointer value (as CFUUIDRef is); use isEqual: to compare two NSUUID instances.

So just do BOOL sameUUID = [uuid1 isEqual:uuid2];

Demerit answered 11/12, 2013 at 17:45 Comment(2)
I would be interested in the reason for a down-vote.Demerit
The "extra method"'s purpose is only to explain the question further. I'd be interested in the reason for a down-vote on the question too ;-).Bodywork
M
3

NSUUID effectively wraps uuid_t.

Solution...

@implementation  NSUUID ( Compare )



- ( NSComparisonResult )  compare : ( NSUUID * )  that
{
   uuid_t   x;
   uuid_t   y;

   [ self  getUUIDBytes : x ];
   [ that  getUUIDBytes : y ];

   const int   r  = memcmp ( x, y, sizeof ( x ) );

   if ( r < 0 )
      return  NSOrderedAscending;
   if ( r > 0 )
      return  NSOrderedDescending;

   return  NSOrderedSame;
}



@end
Magnate answered 29/12, 2017 at 0:3 Comment(1)
This is so important, since NSSortDescriptor uses compare: method. I used NSFetchedRequest with NSPredicate and NSSortDescriptor that was sorting by uuid attribute and got crash (no compare: selector is present with NSUUID) - this fixed it. Thank you.Felisha
B
0

A reasonable simple way to accomplish this is to use string comparison. However, a method that utilizes the underlying CFUUIDRef may be faster.

-(BOOL)isUUID:(NSUUID*)uuid1 equalToUUID:(NSUUID*)uuid2
{
    return [[uuid1 UUIDString] isEqualToString:[uuid2 UUIDString]];
}
Bodywork answered 11/12, 2013 at 17:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.