【发布时间】:2016-06-16 06:55:06
【问题描述】:
更新说明:如果你们想知道,我正在使用Big Nerd Ranch CoreDataStack。
我已经为这个特定问题苦苦挣扎了一段时间。基本上我正在尝试从 CNContactStore 获取联系人并在自定义 NSOperation 中获取 ContactDetails (NSManagedObject)。
现在我正在尝试在单元测试中运行整个过程。到目前为止,这就是我的代码的样子。
单元测试
func testThatLoaderOperationWorks()
{
var coreDataStack: CoreDataStack?
let semaphore = dispatch_semaphore_create(0);
CoreDataStack.constructSQLiteStack(withModelName: "DataModel") { result in
switch result
{
case .Success(let stack):
coreDataStack = stack
case .Failure(let error):
coreDataStack = nil
print (error)
}
dispatch_semaphore_signal(semaphore);
}
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
let contactStore = CNContactStore()
let loaderOperation = LoaderOperation.init(withWorkerContext: (coreDataStack?.newChildContext())!, andContactStore: contactStore)
loaderOperation.completionBlock = {
XCTAssert(true)
}
let operationQueue = NSOperationQueue()
operationQueue.maxConcurrentOperationCount = 1
operationQueue.addOperation(loaderOperation)
loaderOperation.waitUntilFinished()
}
操作子类
override func main()
{
let keysToFetch = [
CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName),
CNContactEmailAddressesKey,
CNContactPhoneNumbersKey,
CNContactImageDataAvailableKey,
CNContactThumbnailImageDataKey]
var allContainers: [CNContainer] = []
do
{
allContainers = try contactStore.containersMatchingPredicate(nil)
}
catch
{
print("Error fetching containers")
}
var contactList: [CNContact] = []
for container in allContainers
{
let fetchPredicate = CNContact.predicateForContactsInContainerWithIdentifier(container.identifier)
do
{
let containerResults = try contactStore.unifiedContactsMatchingPredicate(fetchPredicate, keysToFetch: keysToFetch)
contactList.appendContentsOf(containerResults)
}
catch
{
print("Error fetching results for container")
}
}
self.workerContext.performBlockAndWait
{
let fetchRequest = NSFetchRequest(entityName: "ContactDetails")
do
{
let list = try self.workerContext.executeFetchRequest(fetchRequest)
print("The List: \(list)")
}
catch
{
print(error)
}
}
}
从技术上讲,我想要实现的是能够获取联系人并将它们与我从 CoreData 获取的数据进行交叉引用。但是当我运行 executeFetchRequest 时就会发生死锁。我在某处做错了吗?
【问题讨论】:
标签: ios swift core-data concurrency deadlock