核心数据排序撷取的请求 [英] Core Data Sort Fetched Request

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

问题描述

我需要通过ID获取我的数据库和秩序了。因此,例如,我在数据库中,database_id的和内容的两列。当我的NSLog最后一行我得到内容列中的所有行。但是,我需要根据这些database_id的内容行进行排序是1,2,3,4,5,6(升序)。帮助???

  NSFetchRequest *请求= [[NSFetchRequest的alloc]初始化];    NSEntityDescription *耳鼻喉科= [NSEntityDescription entityForName:@的databaseNameinManagedObjectContext:self.managedObjectContext];
    [要求setEntity:ENT];    NSSortDescriptor * SRT = [NSSortDescriptor sortDescriptorWithKey:@database_id的升序:YES];    [要求setSortDescriptors:[NSArray的arrayWithObject:SRT]];    NSError *错误;
    NSArray的*结果= [self.managedObjectContext executeFetchRequest:请求错误:放大器;错误]    如果(!结果)
    {
        //错误
    }
    NSMutableArray里* myArray的= [[NSMutableArray里的alloc] initWithArray:[结果valueForKey:@内容]];


解决方案

database_id的存储为一个字符串,因此IDS进行排序为字符串:

  1,11,15,2,3,5

最好的解决办法是将存放 database_id的作为一个号码(例如,整型32)
数据库。

作为一种解决方法,你可以保持你的字符串,并使用特殊的比较功能
排序描述:

  NSSortDescriptor * SRT = [NSSortDescriptor sortDescriptorWithKey:@database_id的
                 上行:YES
                  选择:@选择(localizedStandardCompare :)]。

localizedStandardCompare 做了查找类似比较。特别是,含有串
号根据其数值排序

I need to fetch my database and order it by id. So for example, i have 2 columns in database, database_id and content. When I NSLOG last line i get all rows of "content" column. But I need to sort those "content" rows based on database_id which is 1,2,3,4,5,6 (ascending). Help ???

 NSFetchRequest *request = [[NSFetchRequest alloc] init];

    NSEntityDescription *ent = [NSEntityDescription entityForName:@"databaseName" inManagedObjectContext:self.managedObjectContext];
    [request setEntity:ent];

    NSSortDescriptor *srt = [NSSortDescriptor sortDescriptorWithKey:@"database_id" ascending:YES];

    [request setSortDescriptors:[NSArray arrayWithObject:srt]];

    NSError *error;
    NSArray *result = [self.managedObjectContext executeFetchRequest:request error:&error];

    if (!result)
    {
        //error
    }
    NSMutableArray *myArray = [[NSMutableArray alloc] initWithArray:[result valueForKey:@"content"]];

解决方案

Your database_id is stored as a string and therefore the ids are sorted as strings:

1, 11, 15, 2, 3, 5

The best solution would be to store the database_id as a number (e.g. "Integer 32") in the database.

As a workaround, you can keep your strings, and use a special compare function in the sort descriptor:

NSSortDescriptor *srt = [NSSortDescriptor sortDescriptorWithKey:@"database_id"
                 ascending:YES
                  selector:@selector(localizedStandardCompare:)];

localizedStandardCompare does a "Finder-like" comparison. In particular, strings containing numbers are sorted according to their numerical value.

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

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