问题
I am using core data framework to manage objects. I have an entity which has several attributes of decimal types. Among them is an attribute which is mathematically calculated from other attributes. Example:
@interface Marks : NSManagedObject
{
}
@property (nonatomic, retain) NSDecimalNumber * answerGradeA;
@property (nonatomic, retain) NSDecimalNumber * answerGradeB;
@property (nonatomic, retain) NSDecimalNumber * answerGradeC;
@property (nonatomic, retain) NSDecimalNumber * total;
Here I want attribute total = 3xanswerGradeA + 2xanswerGradeB + 1xanswerGradeC.
If it is possible to do like this, then how?
回答1:
The Core Data way is to add 'total' as an attribue to the model and mark it 'transient'. You then provide the implementation in a subclass.
@interface Marks : NSManagedObject
{
}
@property (nonatomic, readonly) NSDecimalNumber* total;
@end
@implementation Marks (Calculated)
- (NSDecimalNumber*) total {
return (3 * [self valueForKey:@"answerGradeA"]) + (2 * [self valueForKey:@"answerGradeB"]) + [self valueForKey:@"answerGradeC"];
}
+ (NSSet *)keyPathsForValuesAffectingTotal
{
return [NSSet setWithObjects:@"answerGradeA", @"answerGradeB", @"answerGradeC", nil];
}
@end
This will ensure proper caching and updating of total.
回答2:
Why not make it a category and compile it in a separate file? (Strictly speaking, total should not be part of CoreData.)
@interface Marks (Calculated)
@property (nonatomic, readonly) NSDecimalNumber* total;
@end
@implementation Marks (Calculated)
- (NSDecimalNumber*) total {
return whatEverYouLike;
}
@end
回答3:
I want to post a little modification to Looji's answer.
@interface Marks : NSManagedObject
{
}
@property (nonatomic, retain) NSDecimalNumber * answerGradeA;
@property (nonatomic, retain) NSDecimalNumber * answerGradeB;
@property (nonatomic, retain) NSDecimalNumber * answerGradeC;
@property (nonatomic, readonly) NSDecimalNumber* total;
@end
@implementation Marks (Calculated)
- (NSDecimalNumber*) total {
return (3 * [self valueForKey:@"answerGradeA"]) + (2 * [self valueForKey:@"answerGradeB"]) + [self valueForKey:@"answerGradeC"];
}
+ (NSSet *)keyPathsForValuesAffectingTotal
{
return [NSSet setWithObjects:@"answerGradeA", @"answerGradeB", @"answerGradeC", nil];
}
@end
来源:https://stackoverflow.com/questions/2745999/how-can-i-set-a-custom-attribute-of-an-nsmanagedobject-which-is-calculated-from