NSSortDiscriptor sort positive values

南笙酒味 提交于 2019-12-25 12:41:50

问题


In my core data, I'm asking for x amount of objects sorting by distance (NSNumber[double]) in ascending order. The problem is it gives me back also negative numbers. I know it make sense but I want only positive numbers, how can I do it?

NSManagedObjectContext *context = generateManagedObjectContext();

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:kCORE_DATA_ALL_TRAPS_ENTITY inManagedObjectContext:context];
    [fetchRequest setEntity:entity];

    // Specify how the fetched objects should be sorted
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:DISTANCE_TO_CLOSE_POINT ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];

    // Limit the restlus to specific number
    [fetchRequest setFetchLimit:numberOfTraps];

    NSError *error = nil;
    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil || fetchedObjects.count == 0) {
        NSLog(@"%s error: %@", __PRETTY_FUNCTION__, error.localizedDescription);
        return nil;
    }

回答1:


Try this,

 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"distance >= %d", 0];

[fetchRequest setPredicate:predicate];



回答2:


As most comments mentioned, you only used NSSortDescriptor while you can also use NSPredicate to do the job.

You can find an example in Apple Docs here. There's a section dedicated to using both.



来源:https://stackoverflow.com/questions/21875056/nssortdiscriptor-sort-positive-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!