在我的应用程序中,其中包含与办公室相关字段的用户列表,我从远程服务器加载两个JSON文件。一个文件包含用户,一个文件包含办公室。将数据从两个JSON文件写入核心数据模型,其关系
我的核心数据模型包含两个实体:用户和办公室。它们彼此相关。在用户中有一个名为office的关系。到现在为止还挺好。
但现在我必须填写实体用户什么是伟大的字段。该列表已经存在。精细!但是当用JSON中的数据填充实体User时,我必须从Office实体中获取适当的managedObject以将其传递给User实体中的User项。
从来就已经定义的写字楼物业在User类
@property (nonatomic, retain) NSManagedObject *office;
但是是什么让我头疼的是我唯一一个从来就在的appDelegate定义managedObjectContext。我将managedObjectContext传递给ListViewController。参见下文:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSManagedObjectContext *context = [self managedObjectContext];
if (!context) {
// Handle the error.
}
// Pass the managed object context to the view controller.
listViewController.managedObjectContextUser = context;
// Override point for customization after application launch.
// Add the tab bar controller's current view as a subview of the window
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque animated:NO];
return YES;
}
,但如果我尝试访问办公室第二managedObject在头从来就先前声明它抛出一个异常:
- (void)updateUsers
{
NSString *users = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:kUsersFilePath]];
if ([users length] == 0)
{
NSLog(@"usersList is == 0");
[users release];
return;
}
SBJsonParser *parser = [[SBJsonParser alloc] init];
usersObject = [[parser objectWithString:users error:nil] copy];
usersList = [usersObject objectForKey:kUsersDataName];
[parser release];
User *user = (User *)[NSEntityDescription entityForName:@"User" inManagedObjectContext:managedObjectContextUser];
NSError *error = nil;
Office *office = (Office *)[NSEntityDescription entityForName:@"Office" inManagedObjectContext:managedObjectContextOffice];
NSLog(@"managedObjectContextOffice: %@", office);
我的问题是我必须创建一个第二个managedObjectContext在我的appDelegate中。一个用户和一个办公室?
或者有没有办法如何处理从ListViewController中只有一个managedObjectContext的两个不同实体获取对象?
我已经做到了。问题是我有两个不同的NSEntityDescription与一个managedObjectContext相关。它没有工作。用户的manageduserContext被办公室的managedObjectContext覆盖。所以我把managedObjectContext加倍到了managedObjectContextOffice和managedObjectContextUser。无论如何,他们指向我的appDelegate中同一个单一的managedContext。奇怪的,但现在它的作品。 – rockstarberlin