iPhone - 排序核心数据实体的结果 [英] iPhone - sorting the results of a core data entity

查看:328
本文介绍了iPhone - 排序核心数据实体的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个核心数据实体,表示产品的属性,如数字,价格等。产品编号是一个NSString属性,并遵循

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

Xy

其中X是数字的数字变量,Y是一个数字。例如。 132.2,99.4等。

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:

代码如下:

+ (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.

我如何做?

感谢。

推荐答案

您可以通过自定义方法对此进行排序。您可以将字符串转换为浮点值,那么您可以很容易地排序。

You can sort this by custom method. you can convert the string into float value then you can easily sort that.

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;
}

这篇关于iPhone - 排序核心数据实体的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆