如何从Realm数据库中计算燃料条目列表中的所有MPG



好的,我要做的是。我有一个"汽车"对象,有一个"燃料条目"数组。每个FuelEntry都有miles、gallonsPumped属性和"fillUp"的Bool值。

我成功地在我的应用程序中计算最新的燃油里程,并使用以下方法显示结果:

    - (float)calculateMPG:(Car*)car {
    RLMResults *fuelResults1 = [car.fuelEntries objectsWhere:@"fillUp = YES"];
    if (fuelResults1.count <= 1) {
        return 0.0;
    } else {
        NSUInteger __block firstEntry = 0;
        NSUInteger __block secondEntry = 0;
        float __block gallonsTotal = 0.0;
        RLMResults *fuelResults = [car.fuelEntries sortedResultsUsingProperty:@"date" ascending:NO];
        NSMutableArray *results = [NSMutableArray new];
        for (FuelEntry *entry in fuelResults) {
            [results addObject:entry];
        }
        [results enumerateObjectsUsingBlock:^(FuelEntry *obj, NSUInteger idx, BOOL *stop) {
            if (obj.fillUp == YES && firstEntry == 0) {
                firstEntry = obj.mileage;
                gallonsTotal += obj.gallons;
            } else if (obj.fillUp == NO && firstEntry == 0) {
                idx++;
            } else if (obj.fillUp == YES && firstEntry != 0) {
                secondEntry = obj.mileage;
                *stop = YES;
            } else {
                gallonsTotal += obj.gallons;
            }
        }];
        return (firstEntry - secondEntry) / gallonsTotal;
    }
}

然而,我被困在如何遍历整个数组并计算所有可能的MPG读数,以便我可以随着时间的推移创建一个报告。

我正在考虑创建一个名为MPGEntry的RLMObject,但如果我可以在需要时计算它,我认为它会更简单。

这是我的"Car"类头文件:

#import <Realm/Realm.h>
#import "OilChange.h"
#import "FuelEntry.h"
#import "ServiceEntry.h"
#import "MonthlyMilesEntry.h"
#import "PhotoObject.h"
#import "MPGEntry.h"
RLM_ARRAY_TYPE(OilChange)
RLM_ARRAY_TYPE(FuelEntry)
RLM_ARRAY_TYPE(MonthlyMilesEntry)
RLM_ARRAY_TYPE(ServiceEntry)

@interface Car : RLMObject
@property NSString *uuid;
@property NSString *name;
@property NSString *make;
@property NSString *VIN;
@property NSInteger year;
//@property BOOL activeCar;
@property NSInteger currentMileage;
@property NSString *driverID;
@property NSInteger oilChangeMiles;
@property NSInteger nextOilChange;

@property RLMArray<PhotoObject> *carPhoto;
@property RLMArray<OilChange> *oilChanges;
@property RLMArray<FuelEntry> *fuelEntries;
@property RLMArray<ServiceEntry> *serviceEntries;
@property RLMArray<MonthlyMilesEntry> *monthlyMilesEntries;
@property RLMArray<MPGEntry> *mpgEntries;
+ (NSDictionary *)defaultPropertyValues;
+ (NSString *)primaryKey;
@end

这是我当前的"FuelEntry"标题:

#import <Realm/Realm.h>
#import "PhotoObject.h"
@interface FuelEntry : RLMObject
@property NSDate *date;
@property NSInteger mileage;
@property double price;
@property double gallons;
@property BOOL fillUp;
@property RLMArray<PhotoObject> *receipts;
+ (NSDictionary *)defaultPropertyValues;
@end

从我能收集到的,你的逻辑在那里抓取所有与汽车相关的燃料条目,但然后使用该循环计算出最近的2个填充事件,以计算出最新的MPG。

既然你已经得到了所有的燃料条目,我不明白为什么不可以遍历整个数组来计算以前的MPG结果。

希望,这只是一个创建另一个数组对象来保存MPG结果的问题,然后每当你到达循环中有'firstEntry'和'secondEntry'的点时,你在那里执行计算,然后重置这两个条目。

如果我在这里错过了什么,请告诉我!

最新更新