这是我的委托.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.h中,我导入了我的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''
如何解决?
答案 0 :(得分:0)
我已经解决了我的问题。我忘了委托它。现在它有效。