这是我的代表.m
#import "TestSaveDataAppDelegate.h"
#import "TestSaveDataViewController.h"
@implementation TestSaveDataAppDelegate
@synthesize window = _window;
@synthesize viewController = _viewController;
@synthesize managedObjectContext = __managedObjectContext;
@synthesize managedObjectModel = __managedObjectModel;
@synthesize persistentStoreCoordinator = __persistentStoreCoordinator;
这是我的 NSManagedObjectContext
- (NSManagedObjectContext *)managedObjectContext
{
if (__managedObjectContext != nil) {
return __managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
__managedObjectContext = [[NSManagedObjectContext alloc] init];
[__managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return __managedObjectContext;
}
这是我的 NSManagedObjectModel
- (NSManagedObjectModel *)managedObjectModel
{
if (__managedObjectModel != nil) {
return __managedObjectModel;
}
__managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
return __managedObjectModel;
}
这是我的 NSPersistentStoreCoordinator
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (__persistentStoreCoordinator != nil) {
return __persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"SaveData.sqlite"];
NSError *error = nil;
__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return __persistentStoreCoordinator;
}
在我的 TestSaveDataViewController.hi 中,导入我的 Savedata.h,就像在我的 Model.xcdatamodeld 中一样,实体名称是 Savedata,这里的属性是带有字符串类型的 saveslot1。
在我的 TestSaveDataViewController.m
@synthesize managedObjectContext;
我有一个这样的按钮
- (IBAction)button1:(id)sender
{
// save text in textfield
Savedata *savedata = (Savedata *)[NSEntityDescription insertNewObjectForEntityForName:@"Savedata" inManagedObjectContext:managedObjectContext];
[savedata setSaveslot1:label1.text];
NSError *error;
if (![managedObjectContext save:&error]) {
// This is a serious error saying the record could not be saved.
// Advise the user to restart the application
}
}
按下按钮时,文本字段中的文本将保存并显示 label1.text 但我收到此错误。
+entityForName: could not locate an NSManagedObjectModel for entity name 'Savedata''
如何解决?