Duplicate cells on each load of tableView from coredata - ios

The view shows duplicate rows for each record in CoreData which keep multiplying on each reload. The code is as under.
What happen is whenever I add record then I view record it shows me the record. Then I click back for the homepage after that when I click on view record I see the copy of same record. So now I have 2 same records. Can anyone please help me with and I think the problem is in table view so here is my table view controller code
import UIKit
import CoreData
var Rec = [Records]()
class TableViewController: UITableViewController {
var firstLoad = true
func nondel() -> [Records]
{
var nodellist = [Records]()
for note in Rec
{
if(note.del == nil)
{
nodellist.append(note)
}
}
return nodellist
}
override func viewDidLoad() {
super.viewDidLoad()
if(firstLoad)
{
firstLoad = false
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context:NSManagedObjectContext = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Records")
do{
let results: NSArray = try context.fetch(request) as NSArray
for result in results {
let note = result as! Records
Rec.append(note)
}
}
catch
{
print("Fetch Failed")
}
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell") as! TableViewCell
let thisrec: Records!
thisrec = nondel()[indexPath.row]
cell.idLB.text = thisrec.id
cell.nameLB.text = thisrec.name
cell.lastLB.text = thisrec.last
cell.genderLB.text = thisrec.gender
cell.ageLB.text = thisrec.age
cell.addressLB.text = thisrec.address
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return nondel().count
}
override func viewDidAppear(_ animated: Bool) {
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
self.performSegue(withIdentifier: "editNote", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "editNote")
{
let indexPath = tableView.indexPathForSelectedRow!
let recDetail = segue.destination as? AddViewController
let selectedCell: Records!
selectedCell = nondel()[indexPath.row]
recDetail!.selectedCell = selectedCell
tableView.deselectRow(at: indexPath, animated: true)
}
}
}

Your code is unbelievable cumbersome.
First of all never declare a data source outside of any class.
Second of all never use a function to build an array as table view data source.
Third of all firstRun is pointless because viewDidLoad is called only once anyway.
Fourth of all rather than filtering the received records manually apply a predicate to the fetch request
Further it's highly recommended to name Core Data entities always in singular form (Record) and to use the specific generic fetch request of this entity.
class TableViewController: UITableViewController {
var records = [Record]()
override func viewDidLoad() {
super.viewDidLoad()
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request : NSFetchRequest<Record> = Record.fetchRequest()
request.predicate = NSPredicate(format: "del != nil")
do {
records = try context.fetch(request)
} catch { print("Fetch Failed", error) }
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell") as! TableViewCell
let thisrec = records[indexPath.row]
cell.idLB.text = thisrec.id
cell.nameLB.text = thisrec.name
cell.lastLB.text = thisrec.last
cell.genderLB.text = thisrec.gender
cell.ageLB.text = thisrec.age
cell.addressLB.text = thisrec.address
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return records.count
}
...

Related

UITableViewCell public function not executing

var list = [String]()
#IBOutlet weak var TableView: UITableView!
override func viewDidLoad() {
self.title = "Routines"
TableView.delegate = self
TableView.dataSource = self
super.viewDidLoad()
}
//refresh view when going back to this viewcontroller
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print("Test Worked")
TableView.reloadData()
}
//generating rows
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return (list.count)
}
//returning text in UITableViewCell
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = UITableViewCell(style:
UITableViewCell.CellStyle.default, reuseIdentifier:
"prototype1")
print("printed")
cell.textLabel?.text = list[indexPath.row]
return cell
}
//deleting rows
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath)
{
if editingStyle == UITableViewCell.EditingStyle.delete{
deleteAllData("ToDo")
self.list.remove(at: indexPath.row)
TableView.reloadData()
}
}
#IBAction func didAdd() {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(identifier: "addRoutinePage")as! addRoutinePage
self.navigationController?.pushViewController(vc, animated: true)
}
//function to get data from core data
func getData()
{
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "ToDo")
request.returnsObjectsAsFaults = false
do{
//fetching data from coredata
let result = try context.fetch(request)
for data in result as! [NSManagedObject]
{
//appending the list from the value in coredata (attribute) or entity
self.list.append(data.value(forKey: "title")as! String)
print("append success")
}
}catch {
print("failed")
}
}
What is wrong with my code? Everything seems to work except for the UITableViewCell, the print command I entered just to check if the function is executed didn't even work. I tried TableView.reloadData() but it still didn't work. Logically if the problem is with the public function or data source or delegate it won't even generate any rows, but rows are generated. I tried resizing the cell height size too but it still won't work. Please help!
There are a few errors with the code:
You need to reload once the data fetching from CoreData is complete.
func getData() {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "ToDo")
request.returnsObjectsAsFaults = false
do {
let result = try context.fetch(request)
for data in result as! [NSManagedObject] {
self.list.append(data.value(forKey: "title")as! String)
}
self.TableView.reloadData()
} catch {
print(error)
}
}
Also, don't forget to call the getData function.
override func viewDidLoad() {
super.viewDidLoad()
title = "Routines"
TableView.delegate = self
TableView.dataSource = self
getData()
}

Insert new row on top of table view with CoreData

I want to make an app using CoreData.
I made the table view and add view controller to add data into Core Data and the table view to retrieve data and everything worked normal. But when I insert a new row from add view controller to the table view, it is going to the bottom of table view. I want to make it insert on top of the table view. I tried different code from the Internet but none worked with my code.
This is Table View Controller:
var List: [NSManagedObject] = []
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
// Configure Table View...
tableView.separatorColor = .clear
}
override func viewDidAppear(_ animated: Bool) {
let application: AppDelegate = UIApplication.shared.delegate as! AppDelegate
let context = application.persistentContainer.viewContext
let get = NSFetchRequest<NSManagedObject>(entityName: "Entity")
List = try! context.fetch(get)
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return List.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MainCell", for: indexPath) as! MainTableViewCell
let data: NSManagedObject = List[indexPath.row]
cell.objectName.text = data.value(forKey: "objectName") as? String
cell.objectPlace.text = data.value(forKey: "placeName") as? String
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 180
}
By default core data objects are fetched in the order they are inserted. To show the last added objects at first just reverse the fetched array.
override func viewDidAppear(_ animated: Bool) {
guard let application = UIApplication.shared.delegate as? AppDelegate else {
return
}
let context = application.persistentContainer.viewContext
let get = NSFetchRequest<NSManagedObject>(entityName: "Entity")
do {
List = try context.fetch(get).reversed()
tableView.reloadData()
} catch let error as NSError {
print(error.userInfo)
}
}
Inside the "NSFetchedResultsController" there is a sortDescriptor
let sortDescriptor = NSSortDescriptor(key: "dateSort", ascending: false)
Create an "entity". When adding to the context, I fill in the date. "Date()"

How to connect to tableview containers?

I am a beginner to Xcode and Swift and I am currently creating an application where the user adds a person on the application and after that it right the amount of money they owe that person or that person owes him/her.
Note: I have used core data to store all the value
I have ViewController called PeopleTableViewController where the user adds the name of the person they owe. Then I have PersonDetailTableViewController which shows the list of details the user owes that particular person the selected in PeopleTableViewController. The problem I am facing is that if I add three people in PeopleTableViewController and when I select any one of the people then I am directed to same tableview in PersonDetailTableViewController but I want different tableviews for different person the user selects in PeopleTableViewController.
PersonDetailTableViewController:
import UIKit
class PersonDetailTableViewController: UITableViewController {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var totalLabel: UILabel?
var person: People?
var owe: Owe?
#IBOutlet var personTable: UITableView!
var dataInfo: [Owe] = []
var selectedObject: [Owe] = []
var balanceAmount = "Balance: "
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (dataInfo.count)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = personTable
.dequeueReusableCell(withIdentifier: "detailsCell", for: indexPath)
cell.textLabel?.text = dataInfo[indexPath.row].name
cell.detailTextLabel?.text = "₹ \(dataInfo[indexPath.row].amount)"
// if dataInfo[indexPath.row].amount < 0 {
// cell.detailTextLabel?.textColor = UIColor.red
// } else {
// cell.detailTextLabel?.textColor = UIColor.green
// }
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedObject = [dataInfo[indexPath.row]]
performSegue(withIdentifier: "addOweDetails", sender: nil)
tableView.deselectRow(at: indexPath, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
getData()
personTable.dataSource = self
addTotalToNav()
print(dataInfo as Any)
}
// MARK: - Table view data source
func addTotalToNav() -> Void {
if let navigationBar = self.navigationController?.navigationBar {
let totalFrame = CGRect(x: 10, y: 0, width: navigationBar.frame.width/2, height: navigationBar.frame.height)
totalLabel = UILabel(frame: totalFrame)
totalLabel?.text = balanceAmount
totalLabel?.tag = 1
totalLabel?.font = UIFont.boldSystemFont(ofSize: 14)
totalLabel?.textColor = UIColor.red
// navigationBar.large = totalLabel?.text
self.title = totalLabel?.text
}
}
func getData() -> Void {
do{
dataInfo = try context.fetch(Owe.fetchRequest())
var total:Double = 0.00
for i in 0 ..< dataInfo.count {
total += dataInfo[i].amount as! Double
}
balanceAmount = "Balance: ₹" + (NSString(format: "%.2f", total as CVarArg) as String)
}
catch{
print("Fetching Failed")
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let vc = segue.destination as! NewOweTableViewController
vc.dataInfo = selectedObject
selectedObject.removeAll()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
getData()
personTable.reloadData()
if (self.navigationController?.navigationBar.viewWithTag(1)?.isHidden == true){
self.navigationController?.navigationBar.viewWithTag(1)?.removeFromSuperview()
addTotalToNav()
}
}
}
PeopleTableViewController:
import UIKit
import CoreData
class PeopleTableViewController: UITableViewController {
#IBOutlet weak var peopleTableView: UITableView!
var people: [People] = []
override func viewDidLoad() {
super.viewDidLoad()
peopleTableView.separatorStyle = .none
// 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
}
//ViewWillAppear allows us to fetch all the data in the backend and help us display to the user
override func viewWillAppear(_ animated: Bool) {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest: NSFetchRequest<People> = People.fetchRequest()
do {
people = try managedContext.fetch(fetchRequest)
peopleTableView.reloadData()
} catch {
print("Could not fetch")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
}
//Following function is called right before the user segues from one viewcontroller to another viewcontroller
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let destination = segue.destination as? PersonDetailTableViewController,
let selectedRow = self.peopleTableView.indexPathForSelectedRow?.row else {
return
}
destination.person = people[selectedRow]
// destination.owe = people[selectedRow]
}
func deletePerson(at indexPath: IndexPath) {
let person = people[indexPath.row]
guard let managedContext = person.managedObjectContext else {
return
}
managedContext.delete(person)
do {
try managedContext.save()
people.remove(at: indexPath.row)
peopleTableView.deleteRows(at: [indexPath], with: .automatic)
} catch {
print("Could not delete")
peopleTableView.reloadRows(at: [indexPath], with: .automatic)
}
}
}
extension PeopleTableViewController{
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return people.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = peopleTableView.dequeueReusableCell(withIdentifier: "peopleCell", for: indexPath)
let person = people[indexPath.row]
cell.textLabel?.text = person.title
return cell
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
deletePerson(at: indexPath)
}
}
}
The following images shows what I exactly require:
PeopleTableViewController
PeopleTableViewController
On clicking Mike I get following:
PersonDetailTableViewController
On clicking John I get following:
PersonDetailTableViewController
I want that the records for Mike and John should be different that is on PersonDetailTableViewController.
You can try (Both in PeopleTableViewController) , create a segue named shoePersonDetails from PeopleTableViewController to PersonDetailTableViewController
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let person = people[indexPath.row]
performSegue(withIdentifier: "shoePersonDetails", sender: person)
tableView.deselectRow(at: indexPath, animated: true)
}
//
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let vc = segue.destination as! PersonDetailTableViewController
vc.dataInfo = sender as! People
}

Saving the right row in a TableView

I`m a Beginner in swift and i have tried to build a shopping list app with a tableView in it. Nearly everthing works, except:
When you reorder the rows, quit the app, and going back, the new row order was not saved.
Any ideas?
This is the important part:
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let movedObject = shoppingList[sourceIndexPath.row]
shoppingList.remove(at: sourceIndexPath.row)
shoppingList.insert(movedObject, at: destinationIndexPath.row)
}
But in will not work.....
Here is the whole code:
import UIKit
import CoreData
var shoppingList: [NSManagedObject] = [ ]
class ShoppingList_1: UIViewController, UITableViewDelegate,UITableViewDataSource {
//Anzahl Spalten -->
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
//**************************
//Zeilen: dynamisch; abhängig von Anzahl items in Liste -->
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return shoppingList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item = shoppingList[indexPath.row]
let cell = Cell.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
// <-- Prototype Cell für Ausschnitt/Sicht des Bildschirms
cell.textLabel?.text = item.value(forKeyPath: "itemName") as? String
cell.detailTextLabel?.text = "\(indexPath.row)"
return cell
}
//free to use
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
print("Daten geladen!\n")
let movedObject = shoppingList[sourceIndexPath.row]
shoppingList.remove(at: sourceIndexPath.row)
shoppingList.insert(movedObject, at: destinationIndexPath.row)
NSLog("%#", "\(sourceIndexPath.row) => \(destinationIndexPath.row) \(shoppingList)")
// To check for correctness enable: self.tableView.reloadData()
}
//*****************************************************************************************************
//Durch wischen entfernen -->
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete
{
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {return}
let managedContext = appDelegate.persistentContainer.viewContext
managedContext.delete(shoppingList[indexPath.row])
do {
try managedContext.save()
shoppingList.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
} catch let err as NSError {
print("12345", err)
}
}
}
#IBOutlet weak var AddButton: UIButton!
#IBOutlet weak var AddItem: UITextField!
#IBOutlet weak var Cell: UITableView!
#IBAction func EditTopRightButton(_ sender: UIBarButtonItem) {
self.Cell.isEditing = !self.Cell.isEditing
sender.title = (self.Cell.isEditing) ? "Done" : "Edit"
}
//Button Action
#IBAction func AddButton2_Test(_ sender: Any) {
print("My test")
let a:Float = 2
let b:Float = 3
let Ergebnis:Float = a+b
print(Ergebnis)
if (AddItem.text != "")
{
self.save(AddItem.text!)
}
Cell.reloadData()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {return}
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Item")
do {
shoppingList = try managedContext.fetch(fetchRequest)
} catch let err as NSError {
print("Failed to fetch items", err)
}
}
func save(_ itemName: String){
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let managedContext = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Item", in: managedContext)!
let item = NSManagedObject(entity: entity, insertInto: managedContext)
item.setValue(itemName, forKey: "itemName")
do {
try managedContext.save()
shoppingList.append(item)
} catch let err as NSError {
print("Failed to save item",err)
}
}
//*****************************************************************************************************
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Cell.delegate = self
Cell.dataSource = self
AddItem.delegate = self
}
//HINZU-->
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
//*****************************************************************************************************
// extensions -->
extension ShoppingList_1 : UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
AddItem.resignFirstResponder()
return true
}
}
//***************************************
Current Working
In your code, Table view is loaded with data from Coredata at viewWillAppear. Data inserted to core data is not updated when you change the order in TableView.
So even you changed order of cell and corder in Array. Every time viewWillAppear calls Data is again fetched from Coredata with no order.
ViewWillAppear will call every time view display in screen. Incase you are coming back to this view from any other presented view ViewWillAppear will call.
Sollution
You can create a new attribute in table describing order of item in Coredata Entity & Sort the item with this order after fetching.
Refer this answer to know how to set display order with core data
https://stackoverflow.com/a/31907857/4845644
Or If your requirement is just to persist order to ViewController instances existence you need to change core data fetch code from viewWillAppear to viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
Cell.delegate = self
Cell.dataSource = self
AddItem.delegate = self
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {return}
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Item")
do {
shoppingList = try managedContext.fetch(fetchRequest)
} catch let err as NSError {
print("Failed to fetch items", err)
}
}

pass data from a table view Controller to View Controller using data stored in core data

I'm a little newbie and I have a doubt, I have a TableViewController and another ViewController that I have as a detailViewController, what I try to do is that when a cell is selected in the tableview, it presents the corresponding data stored in core data for that cell in the detailViewcontroller.
This is the file that controls the tableViewcontroller :
import UIKit
class CostumerTableViewController: UITableViewController {
var costumerArray:[Costumer] = []
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.reloadData()
self.fetchData()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return costumerArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let name = costumerArray[indexPath.row]
cell.textLabel?.text = name.costumerName!
return cell
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
if editingStyle == .delete {
let costumerDelete = costumerArray[indexPath.row]
context.delete(costumerDelete)
(UIApplication.shared.delegate as! AppDelegate).saveContext()
do {
costumerArray = try context.fetch(Costumer.fetchRequest())
} catch {
print(error)
}
}
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let Storyboard = UIStoryboard(name: "Main", bundle: nil)
let DvC = Storyboard.instantiateViewController(withIdentifier: "costumerDetailViewController") as! costumerDetailViewController
let n = costumerArray[indexPath.row]
let Cn = n.costumerName!
DvC.getCostumerName = Cn
self.navigationController?.pushViewController(DvC, animated: true)
}
func fetchData() {
// se crea el context
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
do { // se hace el request del array
costumerArray = try context.fetch(Costumer.fetchRequest())
} catch {
print(error)
}
}
}
In the compilation does not give me any problem, some everything goes well the problem is that it does not present anything in the detail viewController label that in this case I try to send the data from this code.
This is the detailViewController code :
import UIKit
class costumerDetailViewController: UIViewController {
var getCostumerName = String()
#IBOutlet weak var labelName: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
labelName.text! = getCostumerName
}
}
First Check Cn has value or "" on this line.
let Cn = n.costumerName
Change your code in class costumerDetailViewController for declare getCostumerName
var getCostumerName = "" //for avoid crash. if value goes nil.
Use Print() in viewDidLoad and debug it.
Hope this will help you.

Resources