то есть записи разных TableViewCell могли перемешиваться между собой в таблице
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
let section = controller == fetchedResultsController ? 0 : 1
switch type {
case .insert:
myTableView.insertRows(at: [[section, newIndexPath!.row]], with: .automatic)
case .update:
if section == 0 {
let customer = controller.object(at: indexPath!) as! Customer
let cell = myTableView.cellForRow(at: [0, indexPath!.row])
cell!.textLabel?.text = customer.name
} else {
let seller = controller.object(at: indexPath!) as! Seller
let cell2 = myTableView.cellForRow(at: [1, indexPath!.row])
cell2!.textLabel?.text = seller.name_seller
}
case .delete:
myTableView.deleteRows(at: [[section, (indexPath?.row)!]], with: .automatic)
default: break
}
}
func numberOfSections(in tableView: UITableView) -> Int {
//return 2 на
return 1
}
2017-12-23 11:26:01.836140+0200 tableViewWithDifferentEntities[60383:3868739] [error] error: Serious application error. An exception was caught from the delegate of NSFetchedResultsController during a call to -controllerDidChangeContent:. attempt to insert row 0 into section 1, but there are only 1 sections after the update with userInfo (null)
CoreData: error: Serious application error. An exception was caught from the delegate of NSFetchedResultsController during a call to -controllerDidChangeContent:. attempt to insert row 0 into section 1, but there are only 1 sections after the update with userInfo (null)
SAVE
([NSFetchedResultsSectionInfo]?) $R0 = some {
_buffer = {
_storage = (rawValue = __NSAtom @ scalar(0x8000000000000000))
}
}
▿ fatal error: NSArray element failed to match the Swift Array Element type
error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).
The process has been returned to the state before expression evaluation.
import UIKit
import CoreData
class TableView: UIViewController, UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate{
@IBOutlet weak var tableView: UITableView!
var fetchedResultsController = CoreDataManager.instance.fetchedResultsController("Customer", keyForSort: "name")
var fetchedResultsController2 = CoreDataManager.instance.fetchedResultsController("Seller", keyForSort: "name_seller")
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate=self
tableView.dataSource=self
fetchedResultsController.delegate = self
do {
try fetchedResultsController.performFetch()
} catch {
print(error)
}
fetchedResultsController2.delegate = self
do {
try fetchedResultsController2.performFetch()
} catch {
print(error)
}
}
@IBAction func AddCustomer(_ sender: AnyObject) {
performSegue(withIdentifier: "customersToCustomer", sender: nil)
}
@IBAction func AddSeller(_ sender: AnyObject) {
performSegue(withIdentifier: "sellersToSeller", sender: nil)
}
// MARK: - Table View Data Source
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
let sections = fetchedResultsController.sections
return sections![section].numberOfObjects
}
else if section == 1 {
let sections2 = fetchedResultsController2.sections
return sections2![section].numberOfObjects
}
else {
return 1
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "0", for: indexPath) as! TableViewCell
let customer = fetchedResultsController.object(at: indexPath) as! Customer
cell.textLabel?.text = customer.name
return (cell)
} else {
let cell2 = tableView.dequeueReusableCell(withIdentifier: "1", for: indexPath) as! TableViewCell2
let seller = fetchedResultsController2.object(at: indexPath) as! Seller
cell2.textLabel?.text = seller.name_seller
return (cell2)
}
}
// MARK: - Table View Delegate
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let managedObject = fetchedResultsController.object(at: indexPath) as! NSManagedObject
CoreDataManager.instance.managedObjectContext.delete(managedObject)
CoreDataManager.instance.saveContext()
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let customer = fetchedResultsController.object(at: indexPath) as? Customer
performSegue(withIdentifier: "customersToCustomer", sender: customer)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "customersToCustomer" {
let controller = segue.destination as! CustomerViewController
controller.customer = sender as? Customer
}
}
// MARK: - Fetched Results Controller Delegate
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.beginUpdates()
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .insert:
if let indexPath = newIndexPath {
tableView.insertRows(at: [indexPath], with: .automatic)
}
case .update:
if let indexPath = indexPath {
if indexPath.section == 0{
let customer = fetchedResultsController.object(at: indexPath) as! Customer
let cell = tableView.cellForRow(at: indexPath)
cell!.textLabel?.text = customer.name
}
else{
let seller = fetchedResultsController2.object(at: indexPath) as! Seller
let cell2 = tableView.cellForRow(at: indexPath)
cell2!.textLabel?.text = seller.name_seller
}
}
case .move:
if let indexPath = indexPath {
tableView.deleteRows(at: [indexPath], with: .automatic)
}
if let newIndexPath = newIndexPath {
tableView.insertRows(at: [newIndexPath], with: .automatic)
}
case .delete:
if let indexPath = indexPath {
tableView.deleteRows(at: [indexPath], with: .automatic)
}
}
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.endUpdates()
}
}
return sections2![section].numberOfObjects
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var fetchedResultsController2 = CoreDataManager.instance.fetchedResultsController("Seller", keyForSort: "name_seller")
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let customer = fetchedResultsController.object(at: indexPath) as! Customer
//let seller = fetchedResultsController2.object(at: indexPath) as! Seller
let cell = UITableViewCell()
// как сюда вот передать значения еще и с seller.name_seller ???
cell.textLabel?.text = customer.name
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let customer = fetchedResultsController.object(at: indexPath) as? Customer
let seller = fetchedResultsController2.object(at: indexPath) as? Seller
let data:[Any]?
switch type(of: data) {
case is Customer: performSegue(withIdentifier: "customersToCustomer", sender: customer)
case is Seller: performSegue(withIdentifier: "sellersToSeller", sender: seller)
default: print(Error.self)
}
}
Я вызываю в AppDelagate вызываю этот метод, и сравниваю его с условием и в зависимости от этого я инициализирую ViewController входа.
Но для этого мне нужно в метода aaa() достать значения из CoreData, и в зависимости от наличия значений вернуть false/true.
Но после после того, что вы мне сказали у меня есть подозрения, что я никак не смогу сделать fetch, потому он может создаться только после выполнения методов в AppDelagate.
Я правильно думаю?