【问题标题】:NSManagedObjectContext returns nil in Core Data app (iOS)NSManagedObjectContext 在 Core Data 应用程序 (iOS) 中返回 nil
【发布时间】:2012-12-14 11:12:31
【问题描述】:

每次按下按钮时,我都会尝试将字符串保存到数据库中,但是当我运行项目时,我会在控制台上得到它:'NSInvalidArgumentException', reason: '+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'Info''

参考数据模型,我创建了一个 .xcdatamodeld,其中包含一个名为“Info”的实体,其中包含一个名为“path”的属性,其类型为字符串。

我创建了三个函数。 "enterdata" 通过调用 "findData" 检查名称是否可用。如果名称可用,则通过“newData”记录一条新数据,如果不可用,则寻找不同的名称。

我一直在寻找一些类似的问题,我发现了this。它说必须将 de ManagedObjectContext 传递给 View Controller,但我不明白这是什么意思。

这是我的 .h 代码:

@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;

这是我的 .m 代码:​​

#import <CoreData/CoreData.h>

@synthesize managedObjectContext;

int  iSavedNum = 1;
bool bCanSave;

//Enter data
- (IBAction) enterdata:(id)sender {

    //Search if data is already registered
    NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *path = [NSString stringWithFormat:@"%@/info%i.png",docDir, iSavedNum];
    [self findData:path :@"path"];

    //If data is already saved, save it with new name.
    if (bCanSave == NO) {
        for (iSavedNum = 1; bCanSave == YES; iSavedNum++) {
            [self findData:path :@"path"];
            if (bCanSave == YES) {
                [self newData:path :@"path"];
            }
        }
    } else {
        [self newData:path :@"path"];
    }

}

//Input new data
- (void) newData:(NSString *)value:(NSString *)key {

    //Create ManagedObjectContext and ManagedObjectModel
    __0AppDelegate *appDelegate = (__0AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *context = [appDelegate managedObjectContext];
    NSManagedObjectModel *newRecord;

    //Put the data to the Entity
    NSString *entityName = @"Info";
    newRecord = [NSEntityDescription insertNewObjectForEntityForName:entityName inManagedObjectContext:context];
    [newRecord setValue:value forKey:key];

    //Errors management and cheking
    NSError *error;
    [context save:&error];
    NSLog(@"Info Saved. Value: %@ Key: %@", value, key);

}

//Find Data
- (void) findData:(NSString *)valor:(NSString *)key {

    //Create ManagedObjectContext
    __0AppDelegate *appDelegate = (__0AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *context = [appDelegate managedObjectContext];

    //Call the Entity and make a request
    NSString *entityName = @"Info";
    NSEntityDescription *entityDesc = [NSEntityDescription entityForName:entityName inManagedObjectContext:context];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDesc];

    //Create predicate to call specific info
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"(%@ = %@)", key, valor];
    [request setPredicate:pred];

    //Errors management and creation of an array with found info
    NSError *error;
    NSArray *objects = [context executeFetchRequest:request error:&error];

    //Set if the name is avaliable or not
    if ([objects count] == 0) {
        bCanSave = YES;
    } else {
        bCanSave = NO;
    }
}

【问题讨论】:

  • 在哪里创建托管对象上下文? [self managedObjectContext] 是做什么的?错误信息表明它返回nil
  • 在我的 .h 中,我有这个 @property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;,它是在 .m 中合成的,所以理论上是声明的。不是吗?
  • 它被声明为实例变量和属性,但值为nil。您必须从 Core Data 模型和持久存储创建托管对象上下文。也许您是在 AppDelegate 或代码中的其他地方这样做的?然后你必须从那里使用托管对象上下文。
  • 你的意思是:CoreDataAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; NSManagedObjectContext *context = [appDelegate managedObjectContext];
  • 也许你应该单步调试器来找出为什么[appDelegate managedObjectContext]返回nil

标签: objective-c ios core-data nsmanagedobject nsmanagedobjectcontext


【解决方案1】:

它准确地告诉你错误是什么:

nil 不是合法的 NSManagedObjectContext 参数

这意味着在这一行:

newRecord = [NSEntityDescription insertNewObjectForEntityForName:entityName
                                          inManagedObjectContext:context];

变量contextnil。这意味着您的 managedObjectContext 方法无法正常工作。您没有显示此内容,因此我们无法添加更多内容。

【讨论】:

  • 从上面的 cmets 看来,OP 已经在应用程序委托中创建了一个 MOC,但没有从那个“全局”MOC 中设置 managedObjectContext 属性。
【解决方案2】:

application:didFinishLaunchingWithOptions:appDelegate

/*initiate the managed Object Context */  
CoreDataManager *coreDataManager = [CoreDataManager sharedDataManager];
    coreDataManager.managedObjectContext = self.managedObjectContext;

CoreDataManager 是我的核心日期管理器,它明确包含所有核心数据的保存、删除方法

或者

yourClassObject.managedObjectContext = self.managedObjectContext;

所以上下文被初始化

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-04
    • 2010-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多