Home > Articles > Home & Office Computing > Mac OS X

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

Setting Transient Values

Another situation that is quite common with data objects is the use of transient values. In Java, these transient values would be populated as part of the constructor and would be updated in the setter methods of any variables that the transient value is dependent upon. Core Data offers another solution to this situation, again with the help of the key-value protocols. First, the initial calculation of the transient values does not occur inside of the init method. Instead, they occur inside of the awakeFromFetch: method. Like the awakeFromInsert: method above, awakeFromFetch: is called immediately after the object is allocated and instantiated. All the persistent values are populated and available when the awakeFromFetch: method is invoked.

But what if the transient values are not stored in fields, but instead are calculated on the fly? In this situation it is appropriate to flag them as dependent values. By setting them as dependent, they will be automatically flagged as changed as soon as one of the values that they depend on has changed. To flag a transient value as dependent upon another value, the setKeys:triggerChangeNotificationsForDependentKey: method is used. Generally this method is invoked in the initialize: method. For instance, in the ExampleEntity above, there is a transient value called daysSinceModify that is dependent upon an attribute called modifiedDate. Therefore, the initialize method would be as follows:

- (void) initialize {
 NSArray *keys = [NSArray arrayWithObjects:@"modifiedDate", nil];
  [self setKeys:keys
   triggerChangeNotificationsForDependentKey:@"daysSinceModify"];
}

This method, which is part of the key-value protocol, lets the Framework know that if modifiedDate is changed, daysSinceModify will be changed as well. As soon as modifiedDate is changed, all the observers of daysSinceModify will be notified that it has changed as well, which will cause them to call the getter of daysSinceModify. Because daysSinceModify is calculated when its getter is called, all the observers will display the correct information.

  • + Share This
  • 🔖 Save To Your Account