Monday, October 27, 2014

Why a single quote can crash your app

I don't know how many of you use NSPredicate, but you should. It's a great way to filter your data.
In one of my apps, I needed to use a predicate on a list of names that was previously saved to core data. 
It was a very simple section of code:

  NSString *predicateString = [NSString stringWithFormat:@"phoneName =='%@'",withPhoneNameString];
  NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateString];

  [fetchRequest setPredicate:predicate];



The issue was that when I scrolled thru the list, the app crashed.

It was not difficulte tracking down the problem - a single quote character (') at the end of the "withPhoneNameString" (this is something that some last names in Hebrew have).

When the predicate (@"phoneName =='%@'") is used , the single quote in the name takes the place of the string in the predicate definition. 

The solution was also quite simple:

 NSString *predicateString;
    
    //take out the ' char at the end of the name
    
    if ([[withPhoneNameString substringFromIndex:withPhoneNameString.length-1]       isEqualToString:@"'"]) { 

        NSString *newString = 
        [withPhoneNameString substringToIndex:[withPhoneNameString length] -1];

        predicateString = [NSString stringWithFormat:@"phoneName LIKE '%@*'",newString];

    }else{
        
        predicateString = [NSString stringWithFormat:@"phoneName =='%@'",withPhoneNameString];

   }
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateString];

    [fetchRequest setPredicate:predicate];