我遇到了一个我不知道如何解决它的竞争条件。getPurchasedBookTitles 和 getBookEntryIDs 在使用 NSOperationQueue 的不同线程中,它们相互竞争调用 fetchBooks(这是不同类中的方法)。我将 managedObjecContext (parent, child, root) 与 lock/unlock 一起放置以避免赛车问题,但它似乎并没有解决根本问题。
问题是 for 循环中的 book.bookTitle (Book *book in allBooks) 有时会变为 nil 并导致应用程序崩溃或挂起。
提前致谢!
// 在单例类中,dispatch_once
- (NSArray *)getPurchasedBookTitles
{
NSMutableArray *bookTitles = [[NSMutableArray alloc] init];
NSArray *allBooks = [[CoreDataManager sharedInstance] fetchBooks];
for (Book *book in allBooks)
{
if (book.bookTitle != nil && book.is_owned != nil )
if (![bookTitles containsObject:book.bookTitle] && [[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;
}
// 在 coreDataManager 类中 // managedObjectContextChild、managedObjectContext、writerManagedObjectContext 在 appDelegate 和 coreDataManager 类中详细声明和实例化。
- (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:&error];
if (error != NULL)
NSLog(@"Error fetching - %@", error);
[writerManagedObjectContext unlock];
[managedObjectContext unlock];
[managedObjectContextChild unlock];
return results;
}