How do I store a calculated result in UserDefaults to display in a "results" View controller [duplicate] - swift

This question already has answers here:
How can I use UserDefaults in Swift?
(14 answers)
Closed 4 years ago.
First time poster so sorry for the incorrect format/length of the question.
I am building an app in Xcode that allows users to input various inputs among numerous view controllers and then have output in a single view controller with results displayed through labels.
The raw inputted textfield data is stored into UserDefaults and can display them later in the resulting VC with no problem. Im having trouble with calculated outputs (in this example "papiresult") however.
Can anyone provide guidance how to print out the calculated result several view controllers later using UserDefaults?
This is the rough layout
Here is the code I have in the first ViewController:
import UIKit
let userDefaults = UserDefaults()
var papiresult = Double()
class ViewController1: UIViewController, UITextFieldDelegate {
#IBOutlet weak var textField1: UITextField!
#IBOutlet weak var textField2: UITextField!
#IBOutlet weak var textField3: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
textField1.delegate = self
textField2.delegate = self
textField3.delegate = self
}
//Declaring data input into UserDefaults//
#IBAction func sendDataToVC2(_ sender: Any) {
let systPA = Double(textField1.text!)
let diastPA = Double(textField2.text!)
let cvPressure = Double(textField3.text!)
papiresult = ((systPA!-diastPA!)/cvPressure!)
userDefaults.set(textField1.text, forKey: "PASP")
userDefaults.set(textField2.text, forKey: "PADP")
userDefaults.set(textField3.text, forKey: "CVP")
userDefaults.set(papiresult, forKey: "PAPI")
}
}
Here is the code in the last (result) view controller:
import UIKit
class ViewController3: UIViewController {
#IBOutlet weak var label1: UILabel!
#IBOutlet weak var label2: UILabel!
#IBOutlet weak var label3: UILabel!
#IBOutlet weak var label4: UILabel!
#IBOutlet weak var label5: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
//Recalling data from UserDefaults//
override func viewWillAppear(_ animated: Bool) {
if let data1 = userDefaults.object(forKey: "PASP") {
if let message1 = data1 as? String {
self.label1.text = message1}
}
if let data2 = userDefaults.object(forKey: "PADP") {
if let message2 = data2 as? String {
self.label2.text = message2}
}
if let data3 = userDefaults.object(forKey: "CVP") {
if let message3 = data3 as? String {
self.label3.text = message3}
}
if let data4 = userDefaults.object(forKey: "Age") {
if let message4 = data4 as? String {
self.label4.text = message4}
}
if let data5 = userDefaults.object(forKey: "PAPI") {
if let message5 = data5 as? Double {
self.label5.text = "\(message5)"}
}
}

Basically, you should use UserDefaults.standard rather than creating a new instance of UserDefaults class. So I think this code
let userDefaults = UserDefaults()
should be replaced with this:
let userDefaults = UserDefaults.standard

Related

How to pass API image from Table View into another View Controller using didselectrowat

I am a newbie in Swift and I am trying to build an app in which I retrieve plant images and information from this api "https://rapidapi.com/mnai01/api/house-plants2".
I managed to implement a table view in which I display the name and image of each plant in the api, and when I click on any cell in the table view I displayed that certain plant's information in a new view controller.
My problem is that no matter what I tried I couldn't also display the image of that plant in that view controller and I don't know what to do to make it work.
It is also worth to mention that the links for the images are of this format:
img: "http://www.tropicopia.com/house-plant/thumbnails/5556.jpg"
This is the class of the view controller where the image and information should be displayed:
import UIKit
import SDWebImage
class PlantDetailsViewController: UIViewController {
// image view for the plant
#IBOutlet weak var plantImage: UIImageView!
// labels for the plant information
#IBOutlet weak var commonNameLabel: UILabel!
#IBOutlet weak var latinNameLabel: UILabel!
#IBOutlet weak var otherNamesLabel: UILabel!
#IBOutlet weak var categoryLabel: UILabel!
#IBOutlet weak var useLabel: UILabel!
#IBOutlet weak var styleLabel: UILabel!
#IBOutlet weak var familyLabel: UILabel!
#IBOutlet weak var bloomSeasonLabel: UILabel!
#IBOutlet weak var wateringLabel: UILabel!
#IBOutlet weak var idealLightLabel: UILabel!
#IBOutlet weak var growthLabel: UILabel!
#IBOutlet weak var climatLabel: UILabel!
#IBOutlet weak var diseaseLabel: UILabel!
#IBOutlet weak var insectsLabel: UILabel!
#IBOutlet weak var leafColourLabel: UILabel!
#IBOutlet weak var bloomsColourLabel: UILabel!
#IBOutlet weak var availabilityLabel: UILabel!
#IBOutlet weak var bearingLabel: UILabel!
#IBOutlet weak var appealLabel: UILabel!
var plants: Plant?
var strCommonName = ""
var strLatinName = ""
var strOtherNames = ""
var strCategory = ""
var strUse = ""
var strStyle = ""
var strFamily = ""
var strBloomSeason = ""
var strWatering = ""
var strIdealLight = ""
var strGrowth = ""
var strClimat = ""
var strDisease = ""
var strInsects = ""
var strLeafColour = ""
var strBloomsColour = ""
var strAvailability = ""
var strBearing = ""
var strAppeal = ""
override func viewDidLoad() {
super.viewDidLoad()
commonNameLabel.text = strCommonName
latinNameLabel.text = strLatinName
otherNamesLabel.text = strOtherNames
categoryLabel.text = strCategory
useLabel.text = strUse
styleLabel.text = strStyle
familyLabel.text = strFamily
bloomSeasonLabel.text = strBloomSeason
wateringLabel.text = strWatering
idealLightLabel.text = strIdealLight
growthLabel.text = strGrowth
climatLabel.text = strClimat
diseaseLabel.text = strDisease
insectsLabel.text = strInsects
leafColourLabel.text = strLeafColour
bloomsColourLabel.text = strBloomsColour
availabilityLabel.text = strAvailability
bearingLabel.text = strBearing
appealLabel.text = strAppeal
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
This is is the didSelectRowAt function for the table view:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let detail:PlantDetailsViewController = self.storyboard?.instantiateViewController(withIdentifier: "showDetails") as! PlantDetailsViewController
detail.strCommonName = plants[indexPath.row].common_name?.first ?? "N/A"
detail.strLatinName = plants[indexPath.row].latin_name ?? "N/A"
detail.strOtherNames = plants[indexPath.row].other_names ?? "N/A"
detail.strCategory = plants[indexPath.row].categories ?? "N/A"
detail.strUse = plants[indexPath.row].use?.first ?? "N/A"
detail.strStyle = plants[indexPath.row].style ?? "N/A"
detail.strFamily = plants[indexPath.row].family ?? "N/A"
detail.strBloomSeason = plants[indexPath.row].blooming_season ?? "N/A"
detail.strWatering = plants[indexPath.row].watering ?? "N/A"
detail.strIdealLight = plants[indexPath.row].light_ideal ?? "N/A"
detail.strGrowth = plants[indexPath.row].growth ?? "N/A"
detail.strClimat = plants[indexPath.row].climat ?? "N/A"
detail.strDisease = plants[indexPath.row].disease ?? "N/A"
detail.strInsects = plants[indexPath.row].insects?.first ?? "N/A"
detail.strLeafColour = plants[indexPath.row].color_of_leaf?.first ?? "N/A"
detail.strBloomsColour = plants[indexPath.row].color_of_blooms ?? "N/A"
detail.strAvailability = plants[indexPath.row].availability ?? "N/A"
detail.strBearing = plants[indexPath.row].bearing ?? "N/A"
detail.strAppeal = plants[indexPath.row].appeal ?? "N/A"
self.navigationController?.pushViewController(detail, animated: true)
}
In the Manager folder I created class called "APICaller" where I fetch the data from the API. This is the function that does that:
func getAllPlants (completion: #escaping (Result<[Plant], Error>) -> Void) {
guard let url = URL(string: "\(Constants.baseURL)/all/?rapidapi-key=\(Constants.API_KEY)") else {return}
let task = URLSession.shared.dataTask(with: URLRequest(url: url)) { data, _, error in
guard let data = data, error == nil else {return}
do {
let results = try JSONDecoder().decode([Plant].self, from: data)
completion(.success(results))
} catch {
completion(.failure(APIError.failedTogetData))
}
}
task.resume()
}
And finally this is the Plant struct model:
struct Plant: Codable {
let appeal: String?
let availability: String?
let bearing: String?
let blooming_season: String?
let categories: String?
let climat: String?
let color_of_blooms: String?
let color_of_leaf: [String]?
let common_name: [String]?
let disease: String?
let family: String?
let growth: String?
let insects: [String]?
let latin_name: String?
let light_ideal: String?
let other_names: String?
let style: String?
let use: [String]?
let watering: String?
let id: String?
let img: String?
let url: String?
private enum CodingKeys: String, CodingKey {
case appeal = "Appeal"
case availability = "Availability"
case bearing = "Bearing"
case blooming_season = "Blooming season"
case categories = "Categories"
case climat = "Climat"
case color_of_blooms = "Color of blooms"
case color_of_leaf = "Color of leaf"
case common_name = "Common name"
case disease = "Disease"
case family = "Family"
case growth = "Growth"
case insects = "Insects"
case latin_name = "Latin name"
case light_ideal = "Light ideal"
case other_names = "Other names"
case style = "Style"
case use = "Use"
case watering = "Watering"
case id = "id"
case img = "Img"
case url = "Url"
}
}
I think the problem is that each image is a string which contains a link, and to be able to display it in the table view cells I used SDWebImage. The question is how do I do that to display the image in the detail view controller? Thank you for your time. Any help or piece of advice is greatly appreciated :)
UPDATE- I tried to display it like this :
I wrote this in the viewdidload function in the detail view controller:
var selectedImage: String?
if let imageToLoad = selectedImage {
plantImage.image = UIImage(named: imageToLoad)
}
and then I added this line in the didselectrowat function:
detail.selectedImage = plants[indexPath.row].img
It still doesn't work and I don't know what I am doing wrong
Swift 5.5, Xcode 14.2
plantImage.image = UIImage(named: imageToLoad) is wrong, named is to local images, when you want get images from one API, like "http://www.tropicopia.com/house-plant/thumbnails/5556.jpg", you need use :
Github Example: https://github.com/MaatheusGois/answer-75361391
let url = URL(string: image.url)
func downloadImage(from url: URL) {
print("Download Started")
getData(from: url) { data, response, error in
guard let data = data, error == nil else { return }
print(response?.suggestedFilename ?? url.lastPathComponent)
print("Download Finished")
// always update the UI from the main thread
DispatchQueue.main.async { [weak self] in
self?.plantImage.image = UIImage(data: data)
}
}
}
func getData(from url: URL, completion: #escaping (Data?, URLResponse?, Error?) -> Void) {
URLSession.shared.dataTask(with: url, completionHandler: completion).resume()
}
IMPORTANT (Common error)
https://developer.apple.com/forums/thread/119977

displaying user email on viewcontroller gives optional"email adress" [duplicate]

This question already has answers here:
How to remove optional text from json Result In swift
(3 answers)
Optional Text in Alert in ResetPassword - iOS Project using Swift
(2 answers)
Closed 1 year ago.
So I'm using firebase Authentication in my ios app, and I want to display the email address, and Username in UIlabels on a viewcontroller. But when i display the value of Auth.auth().email on a UIlabel, the Label would show Optional"email adress".How do i get rid of the Optional and also how to allow the user to have a display name in firebase Authentication?
import Firebase
import FirebaseAuth
class ProfileViewController: UIViewController {
#IBOutlet weak var profiepic: UIImageView!
#IBOutlet weak var UsernameLabel: UILabel!
#IBOutlet weak var EmailLabel: UILabel!
#IBOutlet weak var league: UILabel!
#IBOutlet weak var Achievements: UIButton!
#IBOutlet weak var resetpasswd: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
UsernameLabel.layer.borderColor = UIColor.black.cgColor
EmailLabel.layer.borderColor = UIColor.black.cgColor
league.layer.borderColor = UIColor.black.cgColor
Achievements.layer.cornerRadius = 55/2
resetpasswd.layer.cornerRadius = 55/2
resetpasswd.layer.borderColor = UIColor.black.cgColor
displayinfo()
}
func displayinfo() {
let user = Auth.auth().currentUser
if let user = user {
// The user's ID, unique to the Firebase project.
// Do NOT use this value to authenticate with your backend server,
// if you have one. Use getTokenWithCompletion:completion: instead.
let email = user.email
let photoURL = user.photoURL
EmailLabel.text = "Email: \(email)"
// ...
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
You need to use if or guard to display string info properly.
Using if:
func displayinfo() {
let user = Auth.auth().currentUser
if let user = user {
if let email = user.email {
EmailLabel.text = "Email: \(email)"
}
if let photoURL = user.photoURL {
...
}
// ...
}
}
Using guard:
func displayinfo() {
guard let user = Auth.auth().currentUser else {
print("No user info found")
return
}
if let email = user.email {
EmailLabel.text = "Email: \(email)"
//EmailLabel.text = "Email: " + email
}
if let photoURL = user.photoURL {
...
}
// ...
}
Let me know if you have any issue in these solutions.
Apart from this, I would rather write UIViewController in this manner which seems to be a more clearer approach.
class ProfileViewController: UIViewController {
#IBOutlet weak var profiepic: UIImageView!
#IBOutlet weak var lblUsername: UILabel! {
didSet {
lblUsername.layer.borderColor = UIColor.black.cgColor
}
}
#IBOutlet weak var lblEmail: UILabel! {
didSet {
lblEmail.layer.borderColor = UIColor.black.cgColor
}
}
#IBOutlet weak var lblLeague: UILabel! {
didSet {
lblLeague.layer.borderColor = UIColor.black.cgColor
}
}
#IBOutlet weak var btnAchievements: UIButton! {
didSet {
btnAchievements.layer.cornerRadius = 55/2
// For button height, instead of 55 here you can use, btnAchievements.bounds.height / 2 or use constrain also to change button height when bound changes
}
}
#IBOutlet weak var btnReset: UIButton! {
didSet {
btnReset.layer.cornerRadius = 55/2
btnReset.layer.borderColor = UIColor.black.cgColor
}
}
private var currentUser: AuthUser? {// Type of Auth.auth().currentUser
didSet {
// Use above code for displayInfo or simply call displayInfo from here
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.currentUser = Auth.auth().currentUser
}
...
}
I hope this would help you designing other UIViewControllers as well.

how to use uistepper to multiply value from segue data transfer [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
So I came across this question that relates to mine and I was wondering how I can do this with a value from a segue data transfer. I want to be able to use my data transfer value as the original value and only have that value change if the stepper value changes.
For example my original value is 5 when the stepper value increases, 10, 15, 20, 25 ... and so on, and same thing for when it decreases. How can I go about doing this?
Here is my data transfer function :
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == Constants.Segues.fromEventDetailsToTicketForm {
guard let user = Auth.auth().currentUser else { return }
let vc = segue.destination as! TicketFormViewController
vc.ticketHolderName = user.displayName
vc.costOfEvent = selectedEventCost
vc.dateOfEvent = selectedEventDate
vc.navigationItem.title = selectedEventName
}
}
Here is the global variables in my destination vc:
#IBOutlet weak var nameOfTicketHolderLabel: UILabel!
#IBOutlet weak var nameOTicketHolderTextF: UITextField!
#IBOutlet weak var numberOfGuestsLabel: UILabel!
#IBOutlet weak var dateOfEventLabel: UILabel!
#IBOutlet weak var actualDateOfEvent: UILabel!
#IBOutlet weak var totalCostOfEventLabel: UILabel!
#IBOutlet weak var actualCostOfEvent: UILabel!
#IBOutlet weak var guestNumberCount: UILabel!
var ticketHolderName: String?
var costOfEvent: String?
var dateOfEvent: String?
var nameOfEvent: String?
And this is the function I use to connect everything:
func dataTransferVerification() {
if let nameToLoad = ticketHolderName {
nameOTicketHolderTextF.text = nameToLoad
}
if let costToLoad = costOfEvent {
actualCostOfEvent.text = costToLoad
}
if let dateToLoad = dateOfEvent {
actualDateOfEvent.text = dateToLoad
}
if let nameToLoad = nameOfEvent {
navigationItem.title = nameToLoad
}
}
The UIStepper func, I have no idea what to put in here:
#IBAction func guestsCount(_ sender: UIStepper) {
guestNumberCount.text = String(Int(sender.value))
}
Now I want to know, with what I got, how to use the cost value and make it original so when the stepper value changes, the original value never changes. Say it's $5.00 when the data transfers over, I only want $5 to be multiplied by the stepper value, I don't want it to change value.
First, you'll want to get a numerical version of your cost string.
At the top of your view controller:
private var costDecimal : Decimal = 0
In your "data transfer" as you call it (you could do this before or after the segue -- doesn't really matter):
let formatter = NumberFormatter()
formatter.numberStyle = .currency
if let number = formatter.number(from: str) {
let amount = number.decimalValue
print(amount)
self.costDecimal = amount
}
(taken from https://stackoverflow.com/a/41884823/560942)
Now, in your stepper:
#IBAction func guestsCount(_ sender: UIStepper) {
guestNumberCount.text = String(Int(sender.value))
//multiply sender.value by the cost that was passed in
let totalCost = Decimal(sender.value) * costDecimal
}

swift Passing data from containverView error

Heloo, i have this problem when im using contaienerView with static tableview. i want to pass my data from my main view controller to my tableview, and im having this break where it said my data is null, but it wasnt null because i already fill that data that i want to pass in. im using firebase and dictionary. heres my code :
my main controller :
class MainController: UITableViewController, AddPatientController {
private var patientLists = [PatientList]() // empty array buat isi list yg isinya nama pasien
var Segue : String = "PatientName"
var Segue2 : String = "PatientNotes"
let user : User = Auth.auth().currentUser!
private var rootRef : DatabaseReference!
override func viewDidLoad() {
super.viewDidLoad()
self.rootRef = Database.database().reference()
populateList()
}
private func populateList() {// 5. func buat fetch data dari db ke hp
self.rootRef.child(self.user.emailWithoutSpecialChar).observe(.value) { (snapshot) in
self.patientLists.removeAll()
let pasienListDict = snapshot.value as? [String:Any] ?? [:] //7. ini berarti return buat kl dict nya kosong, ini buat akses ke valuenya yg isinya itu dict[String:Any]
for (key,_) in pasienListDict {
if let pasienlistdict = pasienListDict[key] as? [String:Any]{
if let pasienlist = PatientList(pasienlistdict) {
self.patientLists.append(pasienlist)
// ini buat ngemasukin ke dalem dictionarynya, ini buat store datanya dan ngambil datanya dari firebase db
}
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
} override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == Segue {
let nc = segue.destination as! UINavigationController
let addPatientName = nc.viewControllers.first as! AddListController
addPatientName.delegate = self
}
else if segue.identifier == Segue2 {
guard let indexPath = self.tableView.indexPathForSelectedRow else {return}
let nc = segue.destination as! PasienProfileController
nc.pasien = self.patientLists[indexPath.row]
}
}
and this is my controller that should recieve the data
class NotesController: UITableViewController, AddNotesDelegate {
var pasien : PatientList!
private var rootRef : DatabaseReference!
var Segue1 : String = "AddNotes"
var Segue2 : String = "PasienNotes"
override func viewDidLoad() {
super.viewDidLoad()
self.title = pasien.name // this is the line where my code break cause it says the data is null
self.rootRef = Database.database().reference()
}
my pasienprofilecontroller and my pasienProfileTableController( the containverView one) :
class PasienTableController: UITableViewController {
#IBOutlet weak var dataKunjunganLbl: UILabel!
#IBOutlet weak var diagnosaPasienLbl: UILabel!
#IBOutlet weak var alergiPasienLbl: UILabel!
var delegete : PasienTableControllerDelegate?
var patientList = [PatientList]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
}
class PasienProfileController: UIViewController {
#IBOutlet weak var TinggiLbl: UILabel!
#IBOutlet weak var beratLbl: UILabel!
#IBOutlet weak var GolDarahLbl: UILabel!
#IBOutlet weak var NamaLbl: UILabel!
#IBOutlet weak var ImagePic: UIImageView!
var pasien : PatientList!
#IBOutlet weak var ContainerView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
self.ImagePic.makeRounded()
self.NamaLbl.text = pasien.name
}
this is the image of my storyboard to get a clear picture of what im trying to do
so my "Patient" view controller is my main controller, which after that it will show the profile pasien controller, which is uiview with container view that contain static tableview. and when i try to hit that " Data Kunjungan Pasien" Cell, it gets the error
so is theres something wrong with my logic? why it keep saying null while it can successfully show the data from Patient view to patientProfileView?
*this is my git if you guys wanna clone and check my error https://gitlab.com/afipermanaa/skripsi.git
Thanks for the help
I dont get it
if you want to pass the data from prepareForSegue with this code
else if segue.identifier == Segue2 {
guard let indexPath = self.tableView.indexPathForSelectedRow else {return}
let nc = segue.destination as! PasienProfileController
nc.pasien = self.patientLists[indexPath.row]
}
to NotesController why do you cast "nc" as PasienProfileController ?
its not the same class
i don't see where you set pasien value.
I hope it helps you if not please explain
cannot comment due to low rep, so I tried to explain it as clear as possible.
you may try to define that variable
private var patientLists = [PatientList]()
as static like below.
private static var patientLists = [PatientList]()
when you try to pass it through segue with this code
let nc = segue.destination as! PasienProfileController
nc.pasien = self.patientLists[indexPath.row]
your class creates a new instance of patientList array when there is 'self'. so, when you define as static, there won't be any new instance of it.
private static var patientLists = [PatientList]()

swift save multiple manage objects

Having issues saving my manage objects within my code. For some reason when i place data in the first view controller everything works well. For instance
I place new categories such as "Fruits", "Dairy", "Meats". The first view controller takes the data. When I click on the specific item such as "Dairy", and put in "Milk" for items within that section. If I go back to the previous view controller and click on "Meats", I see the same data i put in under "Dairy". How do i properly manage my NSManage objects.
Here is my code below.
import UIKit
import CoreData
class HomeSpecificItemViewController: UIViewController {
var selectedItem : [Items] = []
#IBOutlet weak var itemNameTextField: UITextField!
#IBOutlet weak var brandNameTextField: UITextField!
#IBOutlet weak var caloriesTextField: UILabel!
#IBOutlet weak var priceTextField: UILabel!
#IBOutlet weak var amountTextField: UITextField!
#IBOutlet weak var threshHoldNumberField: UITextField!
#IBOutlet weak var stepper: UIStepper!
override func viewDidLoad() {
super.viewDidLoad()
stepper.wraps = true
stepper.autorepeat = true
stepper.maximumValue = 10
// Do any additional setup after loading the view.
}
#IBAction func saveButton(sender: AnyObject) {
let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
let itemDescription = NSEntityDescription.insertNewObjectForEntityForName("Items", inManagedObjectContext: context) as! Items
itemDescription.setValue(itemNameTextField.text, forKey: "Items")
itemDescription.setValue(brandNameTextField.text, forKey: "Items")
do {
try context.save()
}catch _ {
}
/*
let request = NSFetchRequest(entityName: "Items")
let results : [AnyObject]?
do {
results = try context.executeFetchRequest(request)
}catch _ {
results = nil
}
if results != nil {
self.itemDescription = results as! [Items]
}
*/
}
#IBAction func cancelPressed(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
#IBAction func increaseNumberStepper(sender: UIStepper) {
threshHoldNumberField.text = Int(sender.value).description
}
}
Do you have a specific view controller for each category? If so, what you have to do is add predicates to your more specific view controllers.
Something like:
var request = NSFetchRequest(entityName: "Food")
request.predicate = NSPredicate(format: "category == %#", "Meat")
meats = try! context.executeFetchRequest(request)
This would return an array of all Food objects whose category atribute holds the string "Meat".
I was saving my data to core data without properly declaring the manage context and without assigning the text labels to the core data object.
issue resolved!