好的,这是情况。我有两个NSManagedObjects
,分别叫做Store
和Aisle
。从Store
到Aisle
以及从Aisle
到Store
的一对一关系存在一对多关系。如何添加一个NSManagedObject到核心数据并指定它是“父”对象? (iPhone)
我在Core Data中添加了现有的商店,我可以很好地访问。我的问题是,我不知道如何将一个Aisle
对象添加到现有的Store
。我已经尝试撷取Store
,然后加上一个Aisle
对象到.Aisles
组中,我使用由CoreData在Store.h
提供的AddAislesObject:
方法尝试,我已经尝试添加一个Store
对象在Aisle
对象的.Stores
集。
我在看我的SQLite数据库,它看起来像Aisles
正在成功添加,并且它们使用核心数据主键与正确的Store
关联。但由于某种原因,当我尝试检索Aisle
对象时(使用Store
对象的.Aisles
属性),我总是得到零计数。
我也尝试删除我的.sqlite文件无济于事。
有没有人有一些简单的代码,甚至是一个高层次的建议为最好的方式来做到这一点?
谢谢!
--- UPDATE 8/30 0917 CST
我已经采取了以下一些亚当的建议和我的过道肯定保存到核心数据正确。但是,当我尝试从Store对象访问已保存的通道时,我没有收到任何返回的东西。在下面的代码中,您可以看到我使用名称和位置从核心数据检索现有的Store对象(插入时有保护措施以确保此组合是唯一的)。然后,我使用一些NSLog调试来访问返回数组中的单个Store,并使用aisles属性遍历任何过道。忽略调试循环下面的所有内容,因为我还没有完成该方法。
我看到的是aisleList中有零个对象。
-(NSArray *)getAisleListByStore: (Store *)aStore {
// this method should return an NSArray of aisles for aStore
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Store" inManagedObjectContext:context];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name MATCHES[c] %@ AND location MATCHES[c] %@", aStore.name, aStore.location];
[fetchRequest setEntity:entity];
[fetchRequest setPredicate:predicate];
NSError *error;
NSArray *storesList = [context executeFetchRequest:fetchRequest error:&error];
[fetchRequest release];
if (storesList == nil || [storesList count] != 1) {
// error detected
NSLog(@"Error retrieving stores: %@", [error localizedDescription]);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Error retrieving stores" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[alert show];
[alert release];
return nil;
} else {
// get aisles
// debugs
for (Store *theStore in storesList) {
NSLog(@"Name: %@", theStore.name);
NSLog(@"Aisle count: %d", [theStore.aisles count]);
NSSet *aisleList = theStore.aisles;
for (Aisle *theAisle in aisleList) {
NSLog(@"Aisle name: %@", theAisle.name);
}
}
// Store *theStore = [storesList objectAtIndex:0];
// NSArray *aisles = (NSArray *)theStore.aisles;
// return aisles;
}
}
谢谢Adam。我在保存通道时使用了这种通用格式,但是我根据您的示例进行了一些调整。核心数据中确实存在过道,但我仍然无法从Store对象中检索它们。我会在上面的原始问题中发布更多内容。 – Haeriphos 2010-08-30 13:47:48
这个问题实际上是与数据模型有关的。我删除它并重新创建它(没有更改),现在它工作正常。 – Haeriphos 2010-08-31 04:58:38