在coredata中保存并获取时我看到了很多CPU使用情况,有什么方法可以进一步优化它,这是我的代码。
import Foundation
import CoreData
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var ButtonSave: UIButton!
@IBOutlet weak var ButtonFetch: UIButton!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var ButtonDelete: UIButton!
var queue = OperationQueue()
let appDelegate = UIApplication.shared.delegate as! AppDelegate
var ids: [User] = []
override func viewDidLoad() {
super.viewDidLoad()
title = "The List"
tableView.register(UITableViewCell.self,
forCellReuseIdentifier: "Cell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
@IBAction func ActionSave(_ sender: UIButton) {
let context = appDelegate.persistentContainer.viewContext
let entity =
NSEntityDescription.entity(forEntityName: "User",
in: context)!
context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
for i in 0 ..< 10000
{
let person = NSManagedObject(entity: entity,
insertInto: context)
person.setValue("abcdef", forKeyPath: "name")
person.setValue(12+i, forKeyPath: "age")
person.setValue("Male", forKeyPath: "gender")
person.setValue(i, forKeyPath: "id")
}
do {
try context.save()
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
}
@IBAction func ActionDelete(_ sender: UIButton) {
}
@IBAction func ActionFetch(_ sender: UIButton) {
let context = appDelegate.persistentContainer.viewContext
let fetchRequest =
NSFetchRequest<NSManagedObject>(entityName: "User")
let sortDescriptor = NSSortDescriptor(key: "id", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
do {
ids = try context.fetch(fetchRequest) as! [User]
print(ids)
self.tableView.reloadData()
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
}
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return ids.count
}
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath)
-> UITableViewCell {
let cell =
tableView.dequeueReusableCell(withIdentifier: "Cell",
for: indexPath)
let user = self.ids[indexPath.row]
cell.textLabel?.text = "\(user.id)"
return cell
}
}