Вопрос

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;
    }
Это было полезно?

Решение

Try this,

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

[fetchRequest setPredicate:predicate];

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top