【问题标题】:How to sort a fetch in Core Data如何在 Core Data 中对 fetch 进行排序
【发布时间】:2012-06-18 14:33:05
【问题描述】:

我正在获取数据以在 UITableView 中显示它,我进行了获取但我想按创建日期或任何排序方法对它们进行排序。

方法如下:

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

}

【问题讨论】:

    标签: iphone ios xcode core-data


    【解决方案1】:

    这应该可以工作

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

    【讨论】:

    • 非常感谢你.. 它摇滚 :)
    【解决方案2】:

    您有 2 个选择:对结果进行排序或对 NSArray 进行排序:
    NSFetchRequest 可以设置为 NSArrayNSSortDescriptor

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

    还可以对返回的NSArray进行排序(查看NSArray所有以sortedArray...开头的实例方法)
    我建议在使用 CoreData 时使用第一种方法。第二个只是在处理数组时提供信息......

    【讨论】:

      【解决方案3】:

      您可以通过设置 sortDescriptors 来对 fetch 结果进行排序,例如

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多