Reputation: 36013
I have a core data entity that represents the attributes of a product, as number, price, etc. The product number is a NSString property and follows the form
X.y
where X is a number variable of digits and Y is one digit. For example. 132.2, 99.4, etc.
I am querying the database to obtain the list of product numbers in order:
The code is like this:
+ (NSArray*)todosOsItens:(NSString *)pName inManagedObjectContext:(NSManagedObjectContext *)context
{
Product *aProduct = [Product productWithName:pName inManagedObjectContext:context];
NSArray *all = nil;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
request.entity = [NSEntityDescription entityForName:@"Attributes" inManagedObjectContext:context];
request.predicate = [NSPredicate predicateWithFormat:
@"(belongsTo == %@)", aProduct];
[request setResultType:NSDictionaryResultType];
[request setReturnsDistinctResults:YES];
[request setPropertiesToFetch:[NSArray arrayWithObject:item]];
NSSortDescriptor *sortByItem = [NSSortDescriptor sortDescriptorWithKey:@"ProductNumber" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortByItem];
[request setSortDescriptors:sortDescriptors];
NSError *error = nil;
all = [[context executeFetchRequest:request error:&error] mutableCopy];
[request release];
return all;
}
but this query is not returning the sorted results. The results are coming on their natural order on the database.
The order I need is ascending as they were real float numbers.
How do I do that?
thanks.
Upvotes: 0
Views: 1839
Reputation: 12787
You can sort this by custom method. you can convert the string into float value then you can easily sort that.
same as
NSString *a=@"123.45";
float f=[a floatValue];
-(NSMutableArray *)sortByfloatvalue:(NSMutableArray *)array
{
for(int i=0;i<[array count];i++)
{
for(int j=i+1;j<[array count];j++)
{
if([[array objectAtIndex:i] floatValue]>[array objectAtIndex:j])
{
[array exchangeObjectAtIndex:i withObjectAtIndex:j];
}
}
}
return array;
}
Upvotes: 2
Reputation: 3857
You have two options:
Here is code for #2 in your custom class for your Attributes entity for keeping the float value consistant:
- (void)setProductNumber:(NSString *)newProductNumber
{
[self willChangeValueForKey:@"ProductNumber"];
[self setPrimitiveValue:newProductNumber forKey:@"ProductNumber"];
[self didChangeValueForKey:@"ProductNumber"];
// set the mirror value
[self setValue:[NSNumber numberWithFloat:[newProductNumber floatValue]] forKey:@"ProductNumberFloat"];
}
Dont forget to migrate your current data over to this new property.
Upvotes: 0