我正在使用Xcode 7.3和Swift 2.2。我正在尝试获取设备的所有联系人并将其存储在数组中。它在模拟器上可以正常工作,但是在设备(带有378个触点)上进行测试时非常慢。大约需要20到25秒。我放置了多个断点,并注意到从电话中获取联系人花费的时间最多。用表格视图显示从创建的数组中获取的联系人完全不需要时间。这是我的代码,
var results: [CNContact] = []
func retrieveContactsWithStore() {
let contactStore = CNContactStore()
var i = 0
var allContainers: [CNContainer] = []
do {
allContainers = try contactStore.containersMatchingPredicate(nil)
} catch {
print("Error fetching containers")
}
for container in allContainers {
let fetchPredicate = CNContact.predicateForContactsInContainerWithIdentifier(container.identifier)
do {
let containerResults = try contactStore.unifiedContactsMatchingPredicate(fetchPredicate, keysToFetch: [
CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey])
results.appendContentsOf(containerResults)
} catch {
print("Error fetching results for container")
}
}
这就是我填充表格视图的方式。
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel?.text = results[indexPath.row].givenName
cell.detailTextLabel?.text = ((results[indexPath.row].phoneNumbers[0].value as? CNPhoneNumber)?.valueForKey("digits") as? String)
return cell
}
在Debug Navigator中,CPU的峰值也达到98-99%,即Energy Impact-Very High。一旦获取了联系信息,这些信息就会恢复为正常值。
事实证明,获取CNContactPhoneNumbersKey需要花费大量时间。只需获取CNContactGivenNameKey即可快速完成(2-3秒)。我们对此有解决方案吗?
框架或代码没有错。我在其他设备上测试了代码,并且在这里工作正常。它能够在不到一秒钟的时间内获取近900个联系人。
因此问题出在特定于设备的设备上,重新安装iOS并在新iPhone解决后恢复了设备。
如果其他人遇到类似的问题,只需备份您的重要内容(例如联系人,照片等),然后重新安装iOS并将设备还原为新iPhone。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句