One standard method is to define preview
as a transient attribute in the Core Data model (so that the value is not actually stored in the database), and implement a custom getter method. In your case it would look like:
- (NSString *)preview
{
[self willAccessValueForKey:@"preview"];
NSString *preview = [self primitiveValueForKey:@"preview"];
[self didAccessValueForKey:@"preview"];
if (preview == nil) {
if ([self.body length] < 200) {
preview = self.body;
} else {
preview = [self.body substringWithRange:NSMakeRange(0, 200)];
}
[self setPrimitiveValue:preview forKey:@"preview"];
}
return preview;
}
(You can provide custom getter, setter methods for @dynamic properties. However, Core Data
properties are not simply backed up by instance variables. That is the reason why you cannot
access _preview
.)
If you need the preview
to be re-calculated if the body
attribute changes, then you
must also implement a custom setter method for body
that sets preview
back to nil
.
For more information, read Non-Standard Persistent Attributes in the "Core Data Programming Guide".
Update: The current version of the Core Data Programming Guide does
not contain that chapter anymore. You can find an archived version
from the Way Back Machine. Of course this has to be taken with
a grain of salt since it is not part of the official documentation
anymore.