views:

50

answers:

1

Can someone help me with some code to check for duplicates in an NSArray for obective C. I did what I want in vb.net but the translation is hard for me.

'True means no duplicates'
Public Shared Function checkDuplicate(ByVal list As ArrayList) As [Boolean]
    Dim [set] As New HashSet(Of Integer)
    For i As Integer = 0 To list.Count - 1
        Dim val As Boolean = [set].Add(list(i))
        If val = False Then
            Return val
        End If
    Next
    Return True
End Function
+5  A: 
static BOOL CheckDuplicate( NSArray* array )
{
  return [[NSSet setWithArray: array] count] == [array count];
}

P.S. you couldn't do an exact one for one translation of your code, because [NSMutableSet addObject:] doesn't tell you whether anything was added.

P.P.S. I just noticed the "true means no duplicates" comment, so I changed < to == in my code. But it would be better to choose a clearer function name, like HasNoDuplicates.

JWWalker
+1 this is how I'd do it.
Dave DeLong