我有一个使用AppDelegate和MainController的简单应用程序 - 我已将managedObjectContext传递给MainController(我认为已成功)但在向上下文添加对象时收到错误。
代码:
@implementation AppDelegate
-(void)applicationDidFinishLaunching:(NSNotification *) aNotification
{
// this line is wrong: MainController *controller = [[MainController alloc] init];
controller.managedObjectContext = self.managedObjectContext;
}
@interface MainController : NSObject
@property (nonatomic, strong) NSManagedObjectContext *managedObjectContext;
@implementation MainController
-(IBAction)addItem:(id)sender {
NSManagedObject *newObject = [NSEntityDescription
insertNewObjectForEntityForName:@"Person"
inManagedObjectContext: self.managedObjectContext];
//The above line gives an error
错误: + entityForName:nil不是合法的NSManagedObjectContext参数搜索实体名称“Person”
如果我更改代码并在AppDelegate中执行所有操作,那么一切都可以正常运行。
我不确定发生了什么。
[编辑] 我需要从IB中的MainController对象创建一个IBOutlet到AppDelegate - 感谢Nofel。
答案 0 :(得分:0)
我认为应该是这样的:
Person *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:_managedObjectContext];
[person setName:someNameTextField]; // if you want to set some properties
[_managedObjectContext save:nil]
这取决于您如何创建Core-Data模型以及您在appDelegate中使用的内容。 最好的方法是首先观看一些教程或Developer Library。