核心数据NSFetchRequest还获取实体的子对象 [英] Core data NSFetchRequest also fetches children objects of the Entity
问题描述
我是iOS dev和Core Data的新手。我有一个父NSManagedObject
I'm new to iOS dev and Core Data. I have a parent NSManagedObject
@class Units;
@interface Properties : NSManagedObject
@property (nonatomic, retain) NSString * descr;
@property (nonatomic, retain) NSString * address;
@property (nonatomic, retain) NSString * city;
@property (nonatomic, retain) NSString * state;
@property (nonatomic, retain) NSString *zipCode;
@property (nonatomic, retain) NSString * imageKey;
@property (nonatomic, retain) NSString * numberOfUnit;
@property (nonatomic, retain) NSData * thumbnailData;
@property (nonatomic, strong) UIImage * thumbnail;
@property (nonatomic) double orderingValue;
@property (nonatomic, retain) NSSet *units;
和一个孩子:
@class Properties;
@interface Units : Properties
@property (nonatomic, retain) NSString * unitDescr;
@property (nonatomic) int16_t unitNumber;
@property (nonatomic, retain) Properties *property;
当我使用此方法获取父属性以在tableview中显示父属性对象时:
When I fetch the Parent Properties with this method to display the parent Properties objects in a tableview:
- (void)loadAllItems
{
if (!allItems) {
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *e = [[model entitiesByName] objectForKey:@"Properties"];
[request setEntity:e];
NSSortDescriptor *sd = [NSSortDescriptor
sortDescriptorWithKey:@"orderingValue"
ascending:YES];
[request setSortDescriptors:[NSArray arrayWithObject:sd]];
NSError *error;
NSArray *result = [context executeFetchRequest:request error:&error];
if (!result) {
[NSException raise:@"Fetch failed"
format:@"Reason: %@", [error localizedDescription]];
}
allItems = [[NSMutableArray alloc] initWithArray:result];
}
}
我遇到核心数据上下文的问题获取父实体的子对象。我只想返回父对象。
I run in to a problem where the core data context fetches the child objects of the Parent Entity. I just want to return the Parent Objects.
例如,如果我有一个包含3个单位的属性,则属性tableview应该只显示1行,但它显示4行(1个父节点和3个子节点)。
For example, If I have a property with 3 units, the properties tableview should display just 1 row but it is displaying 4 rows (1 parent and 3 childs).
如何返回父对象?
谢谢。
推荐答案
如果您将属性定义为 Units 的父实体,那么每个 Units object也是 Properties 对象。因此,获取属性也会返回所有单位。
If you define Properties as parent entity of Units, then every Units object is also a Properties object. Therefore fetching properties returns also all units.
这可能不是您想要的。您应该只定义 Properties 和 Units 之间的关系,而无需设置父实体(这样两个类都是 NSManagedObject的直接子类
)。
This is probably not what you wanted. You should just define the relationships between Properties and Units, without setting a parent entity (so that both classes are direct subclasses of NSManagedObject
).
备注:我会调用实体 Property 和 Unit ,因为每个实例代表一个属性或单元。
Remark: I would call the entities Property and Unit, because each instance represents a single property or unit.
这篇关于核心数据NSFetchRequest还获取实体的子对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!