在初始化之后,如何将NSManagedObject与上下文相关联? [英] How can I associate an NSManagedObject to the context after it has been initialised?

查看:90
本文介绍了在初始化之后,如何将NSManagedObject与上下文相关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我有一个 NSManagedObject 名为 Items ,并且我想设置 ManagedObjectContext 以后(不是初始化时),我该怎么做?



>

  Items * item = [NSEntityDescription insertNewObjectForEntityForName:@Items
inManagedObjectContext:_context];

自动将其与 _context 关联。 / p>

但是如果我想这样做呢?

  = [[Items alloc] init]; 
item.first = @bla;
item.second = @bla bla;

而我想将该对象传递给另一个方法,然后将其与上下文相关联并保存



所以有办法做一个简单的 item.managedObjectContext = _context 或类似的东西吗?

解决方案

这种方法完全有效...

  Items * item = [[Item alloc] initWithEntity:entity insertIntoManagedObjectContext:nil]; 
item.first = @blah;
item.second = @blah blah;

然后,您可以自由地将此对象传递到需要的位置,将其提交到受管对象上下文,只需插入它并保存。

  [managedObjectContext insertObject:item]; 
NSError * error = nil;
[managedObjectContext save:& error];


For example, if I have an NSManagedObject named Items, and I want to set the ManagedObjectContext later (not when initialised), how would I do that?

At the moment I'm doing this:

Items *item = [NSEntityDescription insertNewObjectForEntityForName:@"Items" 
                                                inManagedObjectContext:_context];

That automatically associates it to _context.

But what if I want to do this:

Items *item = [[Items alloc] init];
item.first = @"bla";
item.second = @"bla bla";

And I would want to pass that object to another method which would then associate it with the context and save it.

So is there any way to just do a simple item.managedObjectContext = _context or something like that?

解决方案

This approach would be perfectly valid...

Items *item = [[Item alloc] initWithEntity:entity insertIntoManagedObjectContext:nil];
item.first = @"blah";
item.second = @"blah blah";

You're then free to pass this object around to where its needed and when you're ready to commit it to a managed object context, simply insert it and save.

[managedObjectContext insertObject:item];
NSError *error = nil;
[managedObjectContext save:&error];

这篇关于在初始化之后,如何将NSManagedObject与上下文相关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆