Objective-C fetch并不总是返回结果

时间:2013-05-30 09:24:31

标签: objective-c core-data uimanageddocument

我有以下代码:

-(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

我的问题是,此代码并不总是返回实体。事实上它实际上从来没有在我第一次打电话时这样做。当我第二次调用它时,以及调试时。

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

谁能帮帮我?

初​​始化:

-(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;
}

2 个答案:

答案 0 :(得分: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
    }
}];

答案 1 :(得分:0)

该代码

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

不正确。

制作

if (results == nil) {
    NSLog (@"%@", [error localizedDescription]);