How to convert NSMutableArray Object NSString data to lowercase in iOS?

I am working with sqlite database. I am fetching text data from sqlite database into NSMutableArray named myArray. This myArray variable has a column named "info" with text data. After I extract this data into NSMutableArray, I would like to convert all text data from sqlite database to lowercase. I wrote the following code in the textDidChange searchBar file.

NSInteger counter = 0;
    for(NSString *nameMe in myArray)
        NSRange r = [[nameMe lowercaseString] rangeOfString:[searchText lowercaseString]];

        if(r.location != NSNotFound)
            if(r.location== 0)
                [tableData addObject:nameMe];



However, an error occurred on the lowercaseString.

This error

2012-03-31 16:28:18.217 SqliteTest[1812:f803] -[MyInfoClass lowercaseString]: unrecognized selector sent to instance 0x6da9210
2012-03-31 16:28:18.276 SqliteTest[1812:f803] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[MyInfoClass lowercaseString]: unrecognized selector sent to instance 0x6da9210'


I think the compiler doesn't know how to convert the object data to lower case. How can I solve this? Can I convert the object data (NSString) to lower case. If it could be, please let me know how to do it. Thank you for your help.


source to share

1 answer

I think the compiler doesn't know how to convert the object data to lower case.

The problem is that objects of type MyInfoClass don't have a method -lowercaseString

. You are iterating over the array, assuming every object in the array is NSString

, but apparently this is not true - there is definitely at least one instance of MyInfoClass in there myArray

. So, one way to fix the problem is that you only add strings to the array.

Here's a shorter, safer way to do what you are doing above:

NSArray *lowercaseArray = [myArray valueForKey:@"lowercaseString"];


NSArray -valueForKey:

will send a message -valueForKey:

with the key you provide to each object in the array and collect the results in the array. Better yet, if any object in the array returns nil, the resulting array will contain the NSNull object at that index. You will want to check for these NSNulls when using an array, but you will not get an exception as in the code.

Update: From the OP's comment, it seems that the reason for converting the array to lowercase is the impossibility of case-insensitive search. It's worth noting that there are better ways to accomplish this. Here are two:

  • Use the NSString method -caseInsensitiveCompare:

    to compare strings if you are doing the comparison yourself.

  • If you are using a predicate to find a match, use the string comparison operators (LIKE, CONTAINS, etc.) with a case insensitive parameter: @ "SELF, eg [c]% @". You can also use diacritical insensitivity: @ "SELF as [cd]% @".



All Articles