我不能得到一个nsmanageobjectcontext [英] I Can't get an nsmanageobjectcontext

查看:454
本文介绍了我不能得到一个nsmanageobjectcontext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我(类似)遵循斯坦福CS193P ios类,我试图得到一个文档上下文,而不必从控制器传递到控制器。 Haggerty教授使用这种方法来获得他的上下文,但它不适合我。我拼写一切正确,我可以得到的上下文,当我通过它,但不是当我得到这种方式。

我缺少的东西?我只想得到我知道我创建的数据库的上下文,而不必传入。

I'm (sort of) following the Stanford CS193P ios class and I'm trying to get a document context without having to pass from controller to controller. Prof Haggerty uses this method to get his context, but it doesn't work for me. I'm spelling everything correctly and I can get the context when I pass it, but not when I get it this way.
Am I missing something?? I just want to get the context for the database that I know I've created without having to pass in.s

- (void)useDemoDocument
{
    NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    url = [url URLByAppendingPathComponent:@"Demo Document"];
    UIManagedDocument *document = [[UIManagedDocument alloc] initWithFileURL:url];

    if (![[NSFileManager defaultManager] fileExistsAtPath:[url path]]) {
        [document saveToURL:url
           forSaveOperation:UIDocumentSaveForCreating
          completionHandler:^(BOOL success) {
              if (success) {
                  self.managedObjectContext = document.managedObjectContext;
                  [self refresh];
              }
          }];
    } else if (document.documentState == UIDocumentStateClosed) {
        [document openWithCompletionHandler:^(BOOL success) {
            if (success) {
                self.managedObjectContext = document.managedObjectContext;
            }
        }];
    } else {
        self.managedObjectContext = document.managedObjectContext;
    }
}


推荐答案

I不要以为你拼错了什么,但你可能对这种方法做错了期望。该方法不返回任何上下文。它将上下文设置为类属性(但仅在某些情况下!)。
所以在调用这个方法后你应该能够访问self.managedObjectContext属性。

I don't think you misspelled anything, but you might have the wrong expectation of what that method is doing. The method is not returning any context. It sets the context as a class property (but only in some cases!). So after calling this method you should be able to access the self.managedObjectContext property.

但是方法实现不是很干净,因此有点危险。它将设置'managedObjectContext'属性仅用于成功的场景。该方法在其他情况下不清除self.managedObjectContext属性,因此在这些情况下,不清楚self.managedObjectContext指向什么。
由于该方法不提供任何成功状态,如果managedObjectContext已正确设置,您将无法信任。

However.. The method implementation is not very clean and therefore a bit dangerous. It will set the 'managedObjectContext' property only for successful scenarios. The method does not clear the self.managedObjectContext property in other cases, so in those cases it's unclear what the self.managedObjectContext is pointing to. Since the method does not provide any success status you can never trust if the managedObjectContext has been set properly.

这篇关于我不能得到一个nsmanageobjectcontext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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