1

我有以下代码:

-(void) readAllQuestions {
    NSLog(@"Reading questions from database");

    NSManagedObjectContext* moc = self.questionsDocument.managedObjectContext;
    moc.mergePolicy = NSRollbackMergePolicy;

    NSFetchRequest* request = [NSFetchRequest fetchRequestWithEntityName:@"QuestionEntity"];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"modified" ascending:YES];
    request.sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];

    NSError *error;
    NSArray* results = [moc executeFetchRequest:request error:&error];
    if (error) {
        NSLog(@"Error: %@", [error localizedDescription]);
    }
    NSLog(@"Read %d question entities", [results count]);
    self.questionsArray = results;
}

questionsDocument 是一个 UIManagedDocument

我的问题是,这段代码并不总是返回实体。事实上,我第一次调用它时它实际上从来没有这样做过。当我第二次调用它时,它也起作用了,当我调试时也是如此。

所以我认为有一个异步问题正在发生。

谁能帮我?

初始化器:

-(id)init {
    if (self = [super init]) {
        [self openDocumentIfItExistsOrCreateNew];
        [self readAllQuestions];
    }
    return self;
}

打开文档的代码:

-(void) openDocumentIfItExistsOrCreateNew {
    QuestionsDocument* document = [self createDocument];

    if (![[NSFileManager defaultManager] fileExistsAtPath:document.fileURL.path]) {
        [self addDocument:document];
    }
    [document openWithCompletionHandler:^(BOOL success) {
        if (success == NO) {
            [NSException
             raise:NSGenericException
             format:@"Could not open the file %@ at %@",
             FILE_NAME,
             document.fileURL];
        }
    }];

    self.questionsDocument = document;
}
4

2 回答 2

1

openWithCompletionHandler异步工作,这意味着它只在后台启动打开文档。完成处理程序块稍后在实际打开文档时调用。

所以你不能[self readAllQuestions]直接在[self openDocumentIfItExistsOrCreateNew]. 例如,您可以将其移动到完成处理程序块中:

[document openWithCompletionHandler:^(BOOL success) {
    if (success) {
         [self readAllQuestions];
         ... update UI (reload table view or whatever you have) ...
    } else {
          // report error
    }
}];
于 2013-05-30T09:52:12.217 回答
0

那个代码

NSArray* results = [moc executeFetchRequest:request error:&error];
if (error) {

是不正确的。

做那个

if (results == nil) {
    NSLog (@"%@", [error localizedDescription]);
于 2013-05-30T09:32:16.793 回答