Reputation: 6431
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.
Upvotes: 0
Views: 115
Reputation: 28419
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
Upvotes: 1
Reputation: 6431
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
Upvotes: 0
Reputation: 4749
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]
Upvotes: 0
Reputation: 1918
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];
Upvotes: 0