0

I'm an extreme beginner at developing iOS applications, so be easy on me :)

I'm creating a core data base where you can add records, then view them on Xcode using Swift 3. I am having some trouble storing/displaying the segmented control for male/female. I can get the text fields and the labels to display correctly but for some reason can't get this working.

friendsViewController.swift

//
//  friendsViewController.swift
// 
//
//  Created by  on 11/10/17.
//  Copyright © 2017 . All rights reserved.
//

import UIKit
import CoreData

class friendsViewController: UIViewController {
    //OUTLETS
    @IBOutlet weak var firstName: UITextField!
    @IBOutlet weak var lastName: UITextField!
    @IBOutlet weak var genderSegControl: UISegmentedControl!
    @IBOutlet weak var ageStepper: UIStepper!

    //AGECOUNT
    @IBOutlet weak var ageLabel: UILabel!
    @IBOutlet weak var address: UITextField!

    var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    //actions
    @IBAction func ageStepperStep(_ sender: UIStepper) {
        let step = Int(sender.value) // using an integer variable
        ageLabel.text = String(step)
        // label1.text = Int(sender.value).description
        // another way without using any integer variable
    }

    //SAVE FRIEND BUTTON
    @IBAction func saveFriendBtn(_ sender: Any) {
        if firstName.text != "" && lastName.text != "" {
            var gender : String?
            if self.genderSegControl.selectedSegmentIndex == 0 {
                gender = "male"
            }
            else {
                gender = "female"
            }

            let newFriend = NSEntityDescription.insertNewObject(forEntityName: "Friends", into: context)
            newFriend.setValue(self.firstName.text, forKey: "firstName")
            newFriend.setValue(self.lastName.text, forKey: "lastName")
            newFriend.setValue(self.address.text, forKey: "address")
            newFriend.setValue(self.ageLabel.text, forKey: "age")
            newFriend.setValue(gender!, forKey: "gender")

            //SAVE THE CONTEXT
            do {
                try context.save()
            }
            catch{
                print(error)
            }
        }
        else {
            print("please enter your first and last name!")
        }
    }
} //end class

friendslistViewController.swift (screen that displays all records in the cells)

//
//  friendslistViewController.swift
// 
//
//  Created by on 11/10/17.
//  Copyright © 2017. All rights reserved.
//

import UIKit
import CoreData

class friendslistViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    //outlets
    @IBOutlet weak var tableView: UITableView!

    var userArray:[Friends] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self

        self.fetchData()
        self.tableView.reloadData()
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return userArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        //save first users data into array
        let name = userArray[indexPath.row]
        cell.textLabel!.text = name.firstName! + " " + name.lastName! + " " + name.age! + " " +
            name.gender! + " " +
            name.address!

        return cell
    }

    func fetchData(){
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

        do{
            userArray = try context.fetch(Friends.fetchRequest())
        }
        catch{
            print(error)
        }
    }
} //end class
rmaddy
  • 314,917
  • 42
  • 532
  • 579
ccodes
  • 17
  • 1
  • 9
  • How does cell view looks like? – Bista Oct 14 '17 at 05:34
  • @Mr.Bista it is set out in rows. https://imgur.com/a/NRCcU – ccodes Oct 14 '17 at 05:51
  • I meant that how the cell elements like first name label, last name label and segment control are place in the cell view in the Xcode not in Simulator. Seems like elements are overlapping each other of the cell height is not mentioned properly. – Bista Oct 14 '17 at 05:53
  • @Mr.Bista I call it with the `cell.textLabel!.text = name.firstName! + " " + name.lastName! + " " + name.age! + " " + name.gender! + " " + name.address!` and it prints accordingly. – ccodes Oct 14 '17 at 05:57
  • @Mr.Bista however, I removed the `name.gender!` bit as it started to crash. – ccodes Oct 14 '17 at 05:59
  • If you change `newFriend.setValue(gender!, forKey: "gender")` to `newFriend.setValue(gender, forKey: "gender")` then what is the behaviour? – 3stud1ant3 Oct 14 '17 at 06:03
  • @3stud1ant3 it was like that initially, but unfortunately still doesn't work – ccodes Oct 14 '17 at 06:07
  • Can you show the `Friends ` entity code? – 3stud1ant3 Oct 14 '17 at 06:09
  • @3stud1ant3 i created the friends entity via the `.xcdatamodeId` file. https://imgur.com/a/f5scg – ccodes Oct 15 '17 at 01:36
  • please add `print(name.gender)` after this statement `let name = userArray[indexPath.row]` and check what it displays? – 3stud1ant3 Oct 15 '17 at 02:34
  • @3stud1ant3 tried both `print(name.gender)` & `print(name.gender!)` to force unwrap it. However, same result. – ccodes Oct 15 '17 at 03:32
  • what does it print? – 3stud1ant3 Oct 15 '17 at 03:33
  • @3stud1ant3 sorry was going to edit my answer. You were too fast for me lol. it prints: `Optional("female") Optional("female") Optional("male") Optional("female") Optional("female")` – ccodes Oct 15 '17 at 03:35
  • @3stud1ant3 so currently there are 5 records and it is picking them up correctly. But it is not displaying in the listView? – ccodes Oct 15 '17 at 03:36
  • Ok just try this: `cell.textLabel!.text = name.gender!` instead of `cell.textLabel!.text = name.firstName! + " " + name.lastName! + " " + name.age! + " " + name.gender! + " " + name.address!` and see what is the behaviour? – 3stud1ant3 Oct 15 '17 at 03:38
  • @3stud1ant3 all sorted. Don't know what the problem was but it seemed to rectified itself, weird. Thanks for the help! :) – ccodes Oct 15 '17 at 03:41
  • lol, weird, you are welcome :) – 3stud1ant3 Oct 15 '17 at 03:42
  • @3stud1ant3 would you by any chance know the answer to this question? https://stackoverflow.com/questions/46751677/pass-core-data-values-into-text-fields-for-editing-saving – ccodes Oct 15 '17 at 04:25

0 Answers0