我是Swift的新手,我编写了一个AppDelegate函数来使用测试plist预加载Core Data。但是,无论我做什么,当我尝试将其加载到tableView中时,它将在上下文中返回“ nil”对象:
在AppDelegate中:
func importPlistSeedData() {
let rulesPath = Bundle.main.path(forResource: "rulesTest", ofType:
"plist")!
let rulesArray = NSArray(contentsOfFile: rulesPath)!
for dict in rulesArray {
let concept = Concept(context: managedContext)
let conceptDict = dict as! [String: Any]
concept.number = conceptDict["id"] as! Int16
concept.title = conceptDict["title"] as? String
concept.titleTranslationRu = conceptDict["titleTranslationRu"] as? String
concept.content = conceptDict["content"] as? String
let imageName = conceptDict["imageName"] as? String
let image = UIImage(named: imageName!)
let photoData = UIImagePNGRepresentation(image!)!
concept.picture1 = NSData(data: photoData) as Data
concept.completed = conceptDict["completed"] as! Bool
}
saveContext()
}
func saveContext () {
guard managedContext.hasChanges else { return }
do {
try managedContext.save()
} catch {
let nserror = error as NSError
print("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
func importPlistDataIfNeeded() {
let fetchRequest = NSFetchRequest<Concept>(entityName: "Concept")
let count = try! managedContext.count(for: fetchRequest)
guard count == 0 else { return }
do {
let results = try managedContext.fetch(fetchRequest)
results.forEach({ managedContext.delete($0) })
saveContext()
importPlistSeedData()
} catch let error as NSError {
print("Error fetching: \(error), \(error.userInfo)")
}
}
在TableView中:
import UIKit
import CoreData
class ConceptsTableViewController: UITableViewController {
var fetchRequest: NSFetchRequest<Concept>?
var concepts: [Concept] = []
var managedContext: NSManagedObjectContext!
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation
bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
guard let model =
managedContext.persistentStoreCoordinator?.managedObjectModel, let
conceptFetchRequest = model.fetchRequestTemplate(forName:
"ConceptFetchRequest") as? NSFetchRequest<Concept> else {return}
self.fetchRequest = conceptFetchRequest
fetchAndReload()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection
section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return concepts.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath:
IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "conceptsCell",
for: indexPath)
let concept = concepts[indexPath.row]
cell.textLabel?.text = "\(concept.number) \(String(describing:
concept.title))"
cell.detailTextLabel?.text = concept.titleTranslationRu
return cell
}
}
extension ConceptsTableViewController {
func fetchAndReload() {
guard let fetchRequest = fetchRequest else {
return
}
do {
concepts = try managedContext.fetch(fetchRequest)
tableView.reloadData()
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
}
}