How can I set a Custom attribute of an NSManagedObject which is calculated from other attributes?

两盒软妹~` 提交于 2019-12-04 16:01:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!