开发者

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

开发者 https://www.devze.com 2022-12-28 23:04 出处:网络
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开发者_StackOverflow中文版 which is mathematically calculate

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开发者_StackOverflow中文版 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?


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.


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号