如何设置从其他属性计算的NSManagedObject的自定义属

如何设置从其他属性计算的NSManagedObject的自定义属

本文介绍了如何设置从其他属性计算的NSManagedObject的自定义属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用核心数据框架来管理对象。我有一个实体有几个属性的十进制类型。其中是从其他属性数学计算的属性。示例:

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;

这里我想要属性 total = 3xanswerGradeA + 2xanswerGradeB + 1xanswerGradeC

如果可以这样做,那么如何?

If it is possible to do like this, then how?

推荐答案

Core Data方法是将total添加为模型的属性并将其标记为transient。然后在一个子类中提供实现。

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.

这篇关于如何设置从其他属性计算的NSManagedObject的自定义属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 02:45