2

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;
}
)
Sudheer Kumar Palchuri
  • 2,919
  • 1
  • 28
  • 38

2 Answers2

2

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.

Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
0

Try this out,

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

Hope it helps :)

sanjaymathad
  • 232
  • 1
  • 5