NSPratik
NSPratik

Reputation: 4846

Case sensitive string comparision issue with NSString

I am keeping a string field in database which should be a unique. So Whenever I want to add a new record for that field using Text field, I will have to test whether such a record already exists or not. If I already added 'A' then I should not even be able to add 'a' later on. But with my code, If I add 'A' then 'A' is not being added but 'a' is being added. so What the solution of this 'Case' issue. I also tried [someString compare:otherString options:NSCaseInsensitiveSearch] but i didn't work for me.

Here is my code:

isDuplicate = FALSE;

            for(int i=0; i<[streetArray count]; i++) // This array contains my field
            {
                strToCompare = (NSString *)[[streetArray objectAtIndex:i]Address];
                if ([[textfield1.text lowercaseString] isEqualToString:[strToCompare lowercaseString]]) // Here I compare stings by making them lower
                {
                    isDuplicate = TRUE;
                    break;
                }
            }

            if(isDuplicate == TRUE)
            {
                [self showAlert:nil withMessage:@"Data already exists"];
            }

Upvotes: 0

Views: 175

Answers (2)

rckoenes
rckoenes

Reputation: 69469

Using the compare:options:NSCaseInsensitiveSearch: method on NSString should work.

if ([@"A" compare:@"a" options:NSCaseInsensitiveSearch] == NSOrderedSame) {
    NSLog(@"same");
}

Upvotes: 1

Cyrille
Cyrille

Reputation: 25144

As stated here you could put all your strings in a NSSet or NSMutableSet, in lowercase form. That would efficiently handle your problem, as that's precisely why NSSets exist.

Upvotes: 2

Related Questions