简体   繁体   English

排序核心数据UITableview

[英]Sort Core Data UITableview

I am trying to sort a tableview based on the value of a core data attribute (name) this is the code I have so far but it does not seem to do anything? 我正在尝试根据核心数据属性(名称)的值对tableview进行排序,这是我到目前为止的代码,但是它似乎没有任何作用?

- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];

// Fetch the devices from persistent data store
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Device"];
self.devices = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];

[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];


[self.tableView reloadData];
}

Thanks for any help. 谢谢你的帮助。

Try to modify your code like this : 尝试像这样修改您的代码:

    - (void)viewDidAppear:(BOOL)animated
    {
    [super viewDidAppear:animated];

    // Fetch the devices from persistent data store
    NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Device"];


    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];
    NSArray *sortDescriptors         = [[NSArray alloc] initWithObjects:sortDescriptor, nil];


    // Set descriptors
    [fetchRequest setSortDescriptors:sortDescriptors];

    self.devices = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];

    [self.tableView reloadData];
}

You need to set the sort descriptor to your fetchrequest. 您需要将排序描述符设置为您的fetchrequest。 Supposing the entity "Device" has an attribute "name" 假设实体“设备”具有属性“名称”

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

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