Reputation: 1352
I have a core data attribute titled 'gLotNumber' which stores alphanumeric strings. Examples include P1
, P5
, 7
, P10
and 11
.
I need to provide a way to search this attribute to the user. The way I can think of providing this is by using NSPredicate on core data using:
[fetchRequest1 setPredicate:[NSPredicate predicateWithFormat:@"(gLotNumber >= 'P1') AND (gLotNumber <= 'P15')"]];
This should result in all entries which start with P
and range between 1 to 15. The above code doesn't produce accurate results at all.
Do you know how this can be achieved?
Upvotes: 0
Views: 215
Reputation: 699
I believe this should work
I don't have a coredata setup hence harcoded some array values.
NSArray *array = @[@{@"gLotNumber":@"P1"},@{@"gLotNumber":@"P15"},@{@"gLotNumber":@"P13"},@{@"gLotNumber":@"P0"},@{@"gLotNumber":@"11"},@{@"gLotNumber":@"10"},@{@"gLotNumber":@"P31"},@{@"gLotNumber":@"P013"},@{@"gLotNumber":@"16"},@{@"gLotNumber":@"P38"}];
NSArray *filtered = [array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF.gLotNumber BEGINSWITH 'P' AND SELF.gLotNumber <= 'P15'"]];
NSSortDescriptor *desc = [NSSortDescriptor sortDescriptorWithKey:@"gLotNumber" ascending:YES comparator:^NSComparisonResult(id obj1,id obj2){
return [obj1 compare:obj2 options:NSNumericSearch];
}];
NSArray *sorted = [filtered sortedArrayUsingDescriptors:@[desc]];
You can set the sort descriptor and predicate to the fetch request
Hope this helps
Upvotes: 0