Sudheer Kumar Palchuri
Sudheer Kumar Palchuri

Reputation: 2954

How can i filter NSMutableArray by firstName with non-alphabetical characters

I want to filter the Array, where name starts with non-alphabetical characters. I want to display the contacts where firstName starts with non-alphabetical characters under different section in table view. I tried below code, but it crashing , please find reason below:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT(firstName BEGINSWITH[c] %@)",arrIndex]; //where arrIndex is the array of alphabetical characeters.
  NSArray  *arrContacts = [arrayTotalContacts filteredArrayUsingPredicate:predicate];

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Can't do a substring operation with something that isn't a string (lhs = iPhone rhs = ( A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z ))'

arrayTotalContacts has the below data:

(
{
    firstName = iPhone;
    lastName = "";
},
{
    firstName = Madhu;
    lastName = "";
},
{
    firstName = "Swa";
    lastName = "";
},
{
    firstName = TechV;
    lastName = "";
},
{
    firstName = Vedika;
    lastName = Vt;
}
)

Upvotes: 2

Views: 908

Answers (2)

Martin R
Martin R

Reputation: 539685

You can use regular expression with a Core Data predicate:

[NSPredicate predicateWithFormat:@"NOT (firstName MATCHES %@)", @"^[A-Za-z].*"]

where ^[A-Za-z].* is a regex for all strings that do start with A-Z or a-z. To make it work with letters from foreign languages as well (e.g. "Ä"), use the Unicode property name:

[NSPredicate predicateWithFormat:@"NOT(firstName MATCHES %@)", @"^\\p{Letter}.*"]

Here ^\\p{Letter}.* is a regex for all strings that start with a letter.

But if this is for a table view, you might better use a fetched results controller and its sectionNameKeyPath parameter. See for example here:

for some examples how to group a table view according to the initial letter. It should be possible to modify the code to group all names that do not start with a letter into a separate group.

Upvotes: 2

sanjaymathad
sanjaymathad

Reputation: 232

Try this out,

NSArray * arrContacts = [arrayTotalContacts  valueForKeyPath:@"firstName"];

Hope it helps :)

Upvotes: 0

Related Questions