CoreData Entity Fetch Request

125 Views Asked by At

I have an entity called TimeInterval whose only attributes are a startDate and finishDate, their type is Date. I obviously do not need to add another attribute called totalTime because that can be calculated by doing: [finishDate timeIntervalSinceDate: startDate]

Can I create a fetched property for the attribute totalTime? If not then what is the best way to go about this without having to add totalTime as an attribute as that seems redundant.

I am new to Core-Data by the way.

4

There are 4 best solutions below

0
On BEST ANSWER

It seems using fetched properties would not work for my situation. A simple category on TimeInterval does the trick:

@implementation TimeInterval (Extras)

-(NSTimeInterval)intervalTime
{
    return [self.finisheDateTime timeIntervalSinceDate: self.startDateTime];
}

@end
1
On

Can I create a fetched property for the attribute totalTime? If not then what is the best way to go about this without having to add totalTime as an attribute as that seems redundant.

My Answer is: No, you should not create its fetched property, because you don't want this as an attribute of your entity so you just create a method lets say

-(NSTimeInterval) getTotalTimeWithStartDate:(NSDate *)startDate withFinishDate:(NSDate *)finishDate{
NSTimeInterval interval = [startDate timeIntervalSinceDate:finishDate];
return interval;

}

//and then call this method using

[self getTotalTimeWithStartDate:startDate withFinishDate:finishDate];
1
On

For doing mathematical calculation on different columns of same table, we are basically using NSExpressionDescription, and setting it to NSFetchRequest as below:

NSExpressionDescription *expressionDesc = [[NSExpressionDescription alloc] init];
[expressionDesc setName:@"totalTime"];
NSExpression *expression = [NSExpression expressionForFunction:@"multiply:by:"
                                                    arguments:@[[NSExpression expressionForKeyPath:@"startDate"],
                                                               [NSExpression expressionForKeyPath:@"finishDate"]];
[expressionDesc setExpression:expression];
[expressionDesc setExpressionResultType:NSInteger64AttributeType];

fetchRequest.propertiesToFetch = @[expressionDesc]
1
On

You can do this with a separate property (or a full-on transient attribute if you like).

Consider something like this...

@interface Item : NSManagedObject
@property (nonatomic, readonly, assign) NSTimeInterval totalTime;
@end


@implementation Item
- (NSTimeInterval)totalTime
{
    [self willAccessValueForKey:@"totalTime"];
    NSDate *finishDate = [self primitiveFinishDate];
    NSDate *startDate = [self primitiveStartDate];
    NSTimeInterval result = [finishDate timeIntervalSinceDate: startDate];
    [self didAccessValueForKey:@"totalTime"];
    return result;
}
@end