Search code examples
iosobjective-ccore-datanspredicatecore-data-migration

Search data form CoreDataBase if search data similar with another data that contain special character


I have implemented Core Database in my Application and fetching data from table. Application requirement is fetch same data if Data contain or not contain hyphen(-)

For Exp1: Table contain below data

   Id       Serialnumber     Name
   1          ABC          ABC2015
   2          A-BC         AB-C001

Table Column SerialNumber contain ABC, A-BC and if user search by AB-C is always consider same as ABC, A-BC

Exp 2:

Id    Serialnumber     Name
1        AB-C         AB-C2015
2        A-BC         A-BC001

Table Column SerialNumber contain AB-C, A-BC and if user search by ABC is always consider same as AB-C, A-BC

Here is my code

+(NSMutableArray*)fetchDataFromCoreDatabase:(NSString*)searchString {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:k_CoreDBEnity_SerailnumerinManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Serialnumber == %@",searchString];
[fetchRequest setPredicate:predicate];
NSError *error = nil;
NSArray *result = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (error) {
    nslog(@"Unable to execute fetch request.");
    error, error.localizedDescription]];
}
return [result mutableCopy];}

So any ideas how to achieve this approach? Thanks in advance!


Solution

  • If it was me, I'd add an extra hidden field that would only be used for searching, which didn't include the hyphen. Then I would remove the hyphens before fetching. In your example:

    • Add a field called something like serialNumberSearch. For your sample data this would always be "ABC", with no -.
    • When searching, if I get A-BC or AB-C, first remove the - and then search for results that match the serialNumberSearch field.

    The result will include anything that matches, according to your description.