I would like to add a custom calculation method to a managed object (which calculates some date based on other properties of this object).
I am not sure if it is better to code this as an transient attribute or to add a property in an category to this managed object.
What do you think?
This is my current code (category):
.h:
@interface IBFinPeriod (DateCalculations)
@property (readonly) NSDate* periodBeginDate;
@end
.m:
#import "IBFinPeriod+DateCalculations.h"
@implementation IBFinPeriod (DateCalculations)
- (NSDate*)periodBeginDate
{
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
if ([self.incPeriodTypeCode isEqualToString:@"M"]) {
offsetComponents.month = - [self.incPeriodLength intValue];
} else if ([self.incPeriodTypeCode isEqualToString:@"W"]) {
offsetComponents.week = - [self.incPeriodLength intValue];
}
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *beginDate = [calendar dateByAddingComponents:offsetComponents toDate:self.EndDate options:0];
return beginDate;
}
@end
Your solution seems fine. If you used a transient property, you’d still need the code to calculate its value, so you’d need a category anyway.
I guess having a transient property would make more sense if you access its value very often, in which case you’d want to cache its value. If you’re going to access the value only a few times, there’s no need for that.