如何设置从其他属性计算的NSManagedObject的Custom属性?

时间:2010-04-30 16:17:36

标签: iphone objective-c core-data nsmanagedobject

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

@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

如果可以这样做,那怎么办?

3 个答案:

答案 0 :(得分:6)

核心数据的方式是将“总数”作为属性添加到模型中,并将其标记为“瞬态”。然后,您将在子类中提供实现。

@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

这将确保正确的缓存和更新总数。

答案 1 :(得分:2)

为什么不将它作为一个类别并在单独的文件中编译? (严格来说,total不应该是CoreData的一部分。)

@interface Marks (Calculated)
@property (nonatomic, readonly) NSDecimalNumber* total;
@end

@implementation Marks (Calculated)
- (NSDecimalNumber*) total { 
  return whatEverYouLike; 
}
@end

答案 2 :(得分:1)

我想对Looji的答案进行一些修改。

@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