根据max属性从数组中获取对象

时间:2013-03-25 17:52:43

标签: objective-c macos cocoa nspredicate

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

我的[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;
}

1 个答案:

答案 0 :(得分:3)

添加排序描述符,按属性对降序进行排序,并将结果数限制为1:

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小于或等于给定值,如果没有找到匹配的对象,则返回一个空数组。