18

I'm working on an app that checks an array to see if it contains a certain string. However, it doesn't seem to be working right, because I think it may be looking at the case of the string. In this line of code, how would I make sure that containsObject: is being case insensitive?

if ([myArray containsObject:term]) {...}

Please ask if you need clarification, and thanks for your help.

(Also, I've found this question: Case insensitive comparison NSString. I don't know if this is what I need, and if it is, how would I use it)

Community
  • 1
  • 1
thekmc
  • 516
  • 5
  • 14

5 Answers5

29
if ([myArray indexOfObjectPassingTest:^(id obj, NSUInteger idx, BOOL *stop){
         return (BOOL)([obj caseInsensitiveCompare:term] == NSOrderedSame);
     }] != NSNotFound) {
    // there's at least one object that matches term case-insensitively
}
Joel Spolsky
  • 33,372
  • 17
  • 89
  • 105
Lily Ballard
  • 182,031
  • 33
  • 381
  • 347
  • Question regarding this solution. how will caseInsensitiveCompare: behave if one of the items in the NSArray is an NSNumber, and not an NSString? will I crash? – Motti Shneor Sep 22 '20 at 08:19
18

Here's an effective approach using key-value coding.

NSArray *strings; // array of strings
if ([[strings valueForKey:@"lowercaseString"] containsObject:[searchString lowercaseString]]) {
   NSLog(@"searchString found");
} else {
   NSLog(@"searchString NOT found");
}

Swift 3 Option:

let things = ["foo", "Bar"]
let searchString = "FOO"

if things.contains(where: { $0.lowercased() == searchString.lowercased() }) {
    print("found searchString")
} else {
    print("searchString not found")
}
Chris Wagner
  • 20,773
  • 8
  • 74
  • 95
7

NSArray is (purposefully) ignorant of what it holds. Thus, it isn't aware of NSString, much less about case sensitivity. You'll have to loop through the items of the array and compare them. You can use one of many different ways of looping through the array :

  • objectEnumerator
  • indexOfObjectPassingTest: which uses blocks to perform your operation.
  • call objectAtIndex: for each item.

I would suggest one of the first 2 options.

0
- (BOOL)containsObject:(id)anObject 

is a convenience method which you cannot apply for your purpose. Here is the documentation discussion:

This method determines whether anObject is present in the array by sending an isEqual: message to each of the array’s objects (and passing anObject as the parameter to each isEqual: message).

The general NSObject method isEqual: method cannot be made to take into consideration the case of string characters. The best solution if you can use blocks (iOS 4) is probably something like Kevin Ballard's proposition. If not then you might have to iterate through the strings.

jbat100
  • 16,757
  • 4
  • 45
  • 70
0
if ([@"Some String" caseInsensitiveCompare:@"some string"] == NSOrderedSame ) {
    //...
}

this one may be useful to you... All The best

Nishith Shah
  • 523
  • 3
  • 16