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

谁说胖子不能爱 提交于 2019-12-03 09:10:49

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