0

我有一组具有属性的对象。我需要获取<=具有价值的对象。

[timeLog time]是以秒为单位的,所以我需要将其转换为分钟,然后将其与Object.conversion_factor. 我最终想要的最大值conversion_factor<=分钟[timeLog time]

这是最好的方法吗?是否有更好的方法(在一个谓词中完成所有这些操作)?

+ (NSNumber *)getTimeUnitForTimeLogEntry:(TimeLog *)timeLog
{
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity =
    [NSEntityDescription entityForName:@"TimeUnit"
                inManagedObjectContext:[[CoreDataHelper sharedInstance] managedObjectContext]];
    [request setEntity:entity];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"conversion_factor <= %i", [OnTimeClasses getMinutesFromTime:[timeLog time]]];
    [request setPredicate:predicate];

    NSError *error;

    NSNumber *returnValue;
    NSArray *array = [[[CoreDataHelper sharedInstance] managedObjectContext] executeFetchRequest:request error:&error];
    NSLog(@"Array: %@", array);
    if (array != nil) {
        NSInteger unit = [[array valueForKeyPath:@"@max.conversion_factor"] integerValue];
        NSPredicate *finalPredicate = [NSPredicate predicateWithFormat:@"conversion_factor == %i", unit];
        [request setPredicate:finalPredicate];
        NSArray *array = [[[CoreDataHelper sharedInstance] managedObjectContext] executeFetchRequest:request error:&error];
        NSLog(@"New array: %@", array);
        TimeUnit *timeUnit = [array objectAtIndex:0];
        returnValue = [timeUnit id];
    }
    else {
        NSString *message = @"Unable to find a good time unit for entry.";
        NSAlert *alert = [NSAlert alertWithMessageText:@"Error" defaultButton:@"OK" alternateButton:nil otherButton:nil informativeTextWithFormat:@"%@", message];
        [alert runModal];
    }

    return returnValue;
}

+ (NSInteger)getMinutesFromTime:(NSString *)time
{
    double minutesFloat = [time doubleValue] / 60;
    NSInteger minutes = round(minutesFloat);

    return minutes;
}
4

1 回答 1

3

添加一个按属性降序排序的排序描述符,并将结果数限制为一个:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"conversion_factor <= %i", [OnTimeClasses getMinutesFromTime:[timeLog time]]];
[request setPredicate:predicate];
NSSortDescriptor *sortDesc = [NSSortDescriptor sortDescriptorWithKey:@"conversion_factor" ascending:NO];
[request setSortDescriptors:@[sortDesc]];
[request setFetchLimit:1];

然后,获取请求返回最大值conversion_factor小于或等于给定值的一个对象,如果没有找到匹配的对象,则返回一个空数组。

于 2013-03-25T18:02:12.677 回答