I have a Core Data project with a sort of “master” entity that holds a year value (int 16) and a few other values. There are a few other “child” entities with many-to-one relationships to this one master. In one of those other entities, I want to set a couple of default values, which are a start and end date. The default values should be the beginning and end of the year assigned to the master entity. So I’ve used this:
- (void) awakeFromInsert {
int currentYear = [[self valueForKeyPath: @"master.year"] intValue];
NSString *currentYearStart = [NSString stringWithFormat: @"%d-01-01 00:00:01 +0000", currentYear];
NSString *currentYearEnd = [NSString stringWithFormat: @"%d-12-31 23:59:59 +0000", currentYear];
[self setStartDate: [NSDate dateWithString: currentYearStart]];
[self setEndDate: [NSDate dateWithString: currentYearEnd]];
}
When I run this, currentYear always ends up being 0, even though the value of master’s “year” attribute is 2011. I’ve tried setting “int currentYear = 2011” and then the code works as expected, so the problem seems to be in the first line. The strange thing is, inside the master entity’s subclass of NSManagedObject, I have lines like:
float total = [[self valueForKeyPath: @"child.@sum.amount"] floatValue];
and this always returns the right amount. I don’t see what the difference is. Can anyone else?
Are you sure that master is set at the time your method is called? Also, the awakeFromInsert docs indicate that you must call
[super awakeFromInsert]first.