2013-10-05 156 views
0

我有一个简单的实体“产品”与属性:核心数据实体

id int64 
sku text 
descript text 
quantity int64 
unitPrice Decimal 
totalPrice Decimal 

我需要的是totalPrice的值是数量的结果+ totalPrice

这样做我需要可能使用NSManagedObject的子类而不是实体。 我从实体生成这样一个类,但我不知道如何实现这个类。 我想添加,删除SET和GET记录。

#import <Foundation/Foundation.h> 
#import <CoreData/CoreData.h> 


@interface Products : NSManagedObject 

@property (nonatomic, retain) NSString * descript; 
@property (nonatomic, retain) NSNumber * id; 
@property (nonatomic, retain) NSNumber * quantity; 
@property (nonatomic, retain) NSString * sku; 
@property (nonatomic, retain) NSDecimalNumber * totalPrice; 
@property (nonatomic, retain) NSDecimalNumber * unitPrice; 

@end 


    #import "Products.h" 


@implementation Products 

@dynamic descript; 
@dynamic id; 
@dynamic quantity; 
@dynamic sku; 
@dynamic totalPrice; 
@dynamic unitPrice; 




@end 

回答

0

只是实现totalPrice作为一个瞬态属性。在Core Data模型编辑器中将其标记为瞬态

然后,在您的托管对象子类中,重写getter。

- (NSNumber*)totalPrice { 
    return @(self.unitPrice.floatValue * self.quantity.intValue); 
} 

如果没有设置其他两个属性,它应该按预期返回0。

+0

谢谢你,但我徘徊了,我应该同时使用核心数据和子类中的实体?现在用上面的代码我不能添加和删除。我连接了ArrayController与子类,而不是核心数据模型,它不起作用。 – user2414590

+0

你描述的是一个不同的问题。你应该先接受答案,并可能提出一个新问题。 – Mundi