Note that there are some explanatory texts on larger screens.

plurals
  1. PORace Condition of coreData executeFetchRequest method cause the issue of nil data
    text
    copied!<p>I run into a race condition that I have no clue how to solve it. getPurchasedBookTitles and getBookEntryIDs are in different threads using NSOperationQueue, they're competing with each other calling fetchBooks (which is a method in a different class). I put managedObjecContext (parent, child, root) with lock/unlock to avoid the problem of racing, but it doesn't seems to solve the root problem. </p> <p>The issue is that book.bookTitle in the for-loop (Book *book in allBooks) will be turned to nil sometime and leads to app crashing or hanging. </p> <p>Thanks in advance!</p> <p>// in a singleton class, dispatch_once</p> <pre><code>- (NSArray *)getPurchasedBookTitles { NSMutableArray *bookTitles = [[NSMutableArray alloc] init]; NSArray *allBooks = [[CoreDataManager sharedInstance] fetchBooks]; for (Book *book in allBooks) { if (book.bookTitle != nil &amp;&amp; book.is_owned != nil ) if (![bookTitles containsObject:book.bookTitle] &amp;&amp; [[book is_owned] boolValue] == YES) [bookTitles addObject:book.bookTitle]; } return bookTitles; } - (NSArray *)getBookEntryIDs { NSMutableArray *bookTitles = [[NSMutableArray alloc] init]; NSArray *allBooks = [[CoreDataManager sharedInstance] fetchBooks]; for (Book *book in allBooks) { if (book.bookTitle != nil) if (![bookTitles containsObject:book.bookTitle]) [bookTitles addObject:book.bookTitle]; } return bookTitles; } </code></pre> <p>// in the class coreDataManager // managedObjectContextChild, managedObjectContext, writerManagedObjectContext are declared and instantiated in the appDelegate and coreDataManager classes in details. </p> <pre><code>- (NSArray *)fetchBooks { NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"bookTitle" ascending:YES]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; NSFetchRequest *request = [[NSFetchRequest alloc] init]; [request setEntity:bookEntity]; [request setPredicate:nil]; [request setSortDescriptors:sortDescriptors]; [managedObjectContextChild lock]; [managedObjectContext lock]; [writerManagedObjectContext lock]; NSError *error = NULL; NSArray *results = [managedObjectContextChild executeFetchRequest:request error:&amp;error]; if (error != NULL) NSLog(@"Error fetching - %@", error); [writerManagedObjectContext unlock]; [managedObjectContext unlock]; [managedObjectContextChild unlock]; return results; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload