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

questionDocument は UIManagedDocument です

私の問題は、このコードが常にエンティティを返すとは限らないことです。実際、私が最初に呼び出したときは実際には決してしません。2回目に呼び出したときと、デバッグしたときにも機能します。

したがって、非同期の問題が発生していると思います。

誰が私を助けることができます?

初期化子:

-(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 に答える