简体   繁体   English

如何对Core Data中的提取进行排序

[英]How to sort a fetch in Core Data

I'm doing a fetch of data to show it in a UITableView, I do the fetch but I want to sort them by date of creation or by any sort method. 我正在获取数据以在UITableView中显示它,我执行获取但我想按创建日期或任何排序方法对它们进行排序。

Here is the method: 这是方法:

-(NSArray *) lesStations {

NSManagedObjectContext *moc = [[AppDelegate sharedAppDelegate]managedObjectContext];

NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
NSEntityDescription *entity =  [NSEntityDescription entityForName:@"Station" inManagedObjectContext:moc];

[fetch setEntity:entity];
NSError *error;

NSArray *result = [moc executeFetchRequest:fetch error:&error];

if (!result) {
    return nil;
}

return result;

}

This should work 这应该工作

-(NSArray *) lesStations {

    NSManagedObjectContext *moc = [[AppDelegate sharedAppDelegate]managedObjectContext];

    NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity =  [NSEntityDescription entityForName:@"Station" inManagedObjectContext:moc];

    [fetch setEntity:entity];
    NSError *error;

    NSArray *result = [moc executeFetchRequest:fetch error:&error];

    if (!result) {
        return nil;
    }

    NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:"creationDate" ascending:YES];



    NSArray *sortedResults = [result sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];

    [sort release];

    return sortedResults;

}

You have 2 options: get the results sorted or sort the NSArray with the results: 您有两个选择:对结果进行排序或对结果进行NSArray排序:
NSFetchRequest could be set a NSArray of NSSortDescriptor NSFetchRequest可以设置为NSSortDescriptorNSArray

NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"place" ascending:NO]; //the key is the attribute you want to sort by
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];

You can also sort the returned NSArray (see all instance methods of NSArray starting with sortedArray... ) 您还可以对返回的NSArray排序(请参阅以sortedArray...开头的NSArray所有实例方法sortedArray...
I suggest using the first approach when working with CoreData. 我建议在使用CoreData时使用第一种方法。 The second one is just informative when working with arrays... 第二个是在使用数组时提供信息......

You can sort fetch results by setting sortDescriptors for fetch, eg 您可以通过为fetch设置sortDescriptors来对获取结果进行排序,例如

fetch.sortDescriptors = [NSArray arrayWithObjects:[[NSSortDescriptor alloc] initWithKey: ascending: selector:], nil];
NSError *error;
NSArray *result = [moc executeFetchRequest:fetch error:&error];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM