Application stuck on splash screen - swift

My application gets stuck on the splash screen when running. It does already have a storyboard entry point which points to the view controller named studentsViewController so I don't know why it isn't working. There is no crash.
StudentsViewController:
import UIKit
class StudentsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var currentClass = VirtualRewardsClient.sharedInstance.getClass()
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
tableView.registerClass(StudentTableViewCell.self, forCellReuseIdentifier: "studentCell")
Class.sharedInstance.addStudent("Dhruv")
Class.sharedInstance.printClass()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Class.sharedInstance.students.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("studentCell") as StudentTableViewCell
return cell
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
VirtualRewardsClient.swift
import UIKit
class VirtualRewardsClient{
class var sharedInstance: VirtualRewardsClient{
struct Static{
static var instance = VirtualRewardsClient()
}
return Static.instance
}
func getClass() -> Class{
if let data = NSUserDefaults.standardUserDefaults().objectForKey(classKey) as? NSData{
let unarc = NSKeyedUnarchiver(forReadingWithData: data)
unarc.setClass(Class.self, forClassName: "Class")
let currentClass = unarc.decodeObjectForKey("root") as Class
Class.sharedInstance.students = currentClass.students
Class.sharedInstance.teacher = currentClass.teacher
return currentClass
}
return Class()
}
}
Class.swift
import Foundation
import UIKit
let classKey = "CLASS_KEY"
class Class: NSObject{
let defaults = NSUserDefaults.standardUserDefaults()
class var sharedInstance: Class{
struct Static{
static var instance: Class = VirtualRewardsClient.sharedInstance.getClass()
}
return Static.instance
}
var students:[Student] = [Student]()
var teacher = Teacher(currentClass: sharedInstance)
func addStudent(name: String, value: Int){
students.append(Student(name: name, startingPoints: value))
defaults.setObject(NSKeyedArchiver.archivedDataWithRootObject(Class.sharedInstance), forKey: classKey)
VirtualRewardsClient.sharedInstance.getClass()
}
func addStudent(name: String){
students.append(Student(name: name))
defaults.setObject(NSKeyedArchiver.archivedDataWithRootObject(Class.sharedInstance), forKey: classKey)
VirtualRewardsClient.sharedInstance.getClass()
}
func printClass(){
for i in students{
println("Student: \(i.name), Points: \(i.points)")
}
}
}

Related

Passing access from tableViewController to another view controller

I have spent a fair bit of time on this and still can't seem to figure out what I'm doing wrong.
I would like to run the reloadData() function in my own function on another view controller than the tableViewController but I get the error Type 'HomeViewController' has no member 'reloadData'.
HomeViewController:
import UIKit
import CoreData
class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var index = ""
var item : [ListItem] = [] //listName
var listName = [""]
override func viewDidLoad() {
super.viewDidLoad()
self.homeListsTableView.delegate = self
self.homeListsTableView.dataSource = self
homeListsTableView.reloadData()
//List Names
//List Items - Within a list Name
let listItem1 = ListItem()
listItem1.name = "" //Update so names are updated via append the ListItem Array
listItem1.location = ""
item.append(listItem1)
let listItem2 = ListItem()
listItem2.name = ""
listItem2.location = ""
item.append(listItem2)
}
#IBOutlet weak var homeListsTableView: UITableView!
#IBAction func templatesButton(_ sender: Any) {
tabBarController?.selectedIndex = 2
}
override func viewWillAppear(_ animated: Bool) {
if let context = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext {
if let coreDataListItems = try? context.fetch(ListName.fetchRequest()) as? [ListName] {
print(coreDataListItems)
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return listName.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = listName[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// performSegue(withIdentifier: "goToItems", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let vc = segue.destination as! ListNameViewController
vc.homeListsTableViewVC = homeListsTableView
}
}
ListName View Controller:
import UIKit
import CoreData
class ListNameViewController: UIViewController, UITableViewDelegate {
// var listName = [""]
let context = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext
var homeListsTableViewVC = HomeViewController.self
override func viewDidLoad() {
super.viewDidLoad()
}
#IBOutlet weak var listNameValue: UITextField!
#IBOutlet weak var locationOption: UITextField!
#IBOutlet weak var createButtonChange: UIButton!
#IBAction func createButton(_ sender: Any) {
let newList = ListName(context: context!)
newList.listName = listNameValue.text
// let location = locationOption.text!
//tabBarController?.selectedIndex = 0
//performSegue(withIdentifier: "home", sender: nil)
}
func saveList() {
do {
try context!.save()
} catch {
print("Error saving context \(error)")
}
homeListsTableViewVC.reloadData()
}
}
I'm trying to use the prepare for segue function to pass the homeListsTableView data to then use the reloadData() function. Could someone tell me what I'm doing wrong?
Thanks!
You can use delegate or closure to update your tableview.. here is pointers of how you can use closure in your classes to update view
class ListNameViewController: UIViewController, UITableViewDelegate {
var callback: (()->())?
//....
func saveList() {
do {
try context!.save()
} catch {
print("Error saving context \(error)")
}
callback?()
}
}
And while creating ListNameViewController
class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let vc = segue.destination as! ListNameViewController
vc.callback = { [weak self] in
self?.homeListsTableView.reloadData()
}
}
}

not able to load data with ViewModel

the tableView dataSource is properly set up in the IB
the viewController identity is properly set as well in the IB
this is my viewModel
class StatusCodeViewModel {
let apiClient = APIClient.shared
var statusCodes: [StatusCode] = []
let identifier = "statusCodeCell"
init() {}
func loadStatusCodes() {
apiClient.execute(service: .statusCode) { statusCodes in
self.statusCodes = statusCodes
}
}
}
and the viewController in which I want to load data
class ViewController: UIViewController {
#IBOutlet weak var tableView: UITableView!
var viewModel: StatusCodeViewModel? {
didSet {
if viewModel!.statusCodes.count > 0 {
self.tableView.reloadData()
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
viewModel = StatusCodeViewModel()
viewModel!.loadStatusCodes()
}
}
extension ViewController : UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let statusCodes = viewModel!.statusCodes as? [StatusCode] {
return statusCodes.count
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: viewModel!.identifier)
cell?.textLabel!.text = viewModel!.statusCodes[indexPath.row].title
return cell!
}
}
the data count is 0 and no data is shown in the tableView
You have did set on view model which will occur on initialisation.
You will have to implement some kind of callback when the api returns the call - easiest way would be protocol.
protocol StatusCodeViewModelDelegate {
func callFinished()
}
class StatusCodeViewModel {
let apiClient = APIClient.shared
var statusCodes: [StatusCode] = []
let identifier = "statusCodeCell"
var delegate : StatusCodeViewModelDelegate?
init() {}
func loadStatusCodes() {
apiClient.execute(service: .statusCode) { statusCodes in
self.statusCodes = statusCodes
delegate?.callFinished()
}
}
}
Then in your viewController:
override func viewDidLoad() {
super.viewDidLoad()
viewModel = StatusCodeViewModel()
viewModel.delegate = self
viewModel!.loadStatusCodes()
}
func callFinished() {
self.tableView.reloadData()
}
Don't forget to extend for delegate you just made:
class ViewController: UIViewController, StatusCodeViewModelDelegate {
Or, as #rmaddy suggested, in View model change loadStatusCodes to:
func loadStatusCodes(completion: #escaping () -> Void) {
apiClient.execute(service: .statusCode) { statusCodes in
self.statusCodes = statusCodes
}
}
Then, in the viewDidLoad:
override func viewDidLoad() {
super.viewDidLoad()
viewModel = StatusCodeViewModel()
viewModel!.loadStatusCodes {
self.tableView.reloadData()
}
}
//This would do !
func loadStatusCodes(completion: #escaping () -> Void) {
apiClient.execute(service: .statusCode) { statusCodes in
self.statusCodes = statusCodes
completion()
}
}
// And in ViewController:
override func viewDidLoad() {
super.viewDidLoad()
viewModel = StatusCodeViewModel()
viewModel?.loadStatusCodes() {
self.tableView.reloadData()
}
}

Swift 4 delegates and passing textfield data

I am trying to make an app using the GoogleBooks API where I can use either a title or author or both to search for books. I am currently just working on the delegate portion to be able to pass the search terms to the results table view. However, I am getting errors with the variables I am using being let constants but I have them declared as var so I'm not sure where I am messing up.
This is the UIViewController code for the view with the two search boxes and the button:
import UIKit
protocol ViewControllerDelegate: class {
func searchInput(_ titleFromSearch: String?, authorFromSearch: String?)
}
class ViewController: UIViewController {
#IBOutlet weak var titleFromSearch: UITextField!
#IBOutlet weak var authorFromSearch: UITextField!
weak var delegate: ViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
titleFromSearch.delegate = self
authorFromSearch.delegate = self
}
override func touchesEnded(_ touches: Set<UITouch>, with event:
UIEvent?) {
super.touchesEnded(touches, with: event)
titleFromSearch.resignFirstResponder()
authorFromSearch.resignFirstResponder()
}
}
extension ViewController: UITextFieldDelegate {
func fieldsDidEndEditing(_ titleEntered: UITextField, authorEntered:
UITextField) {
if let delegateController = delegate {
delegateController.searchInput(titleFromSearch.text,
authorFromSearch: authorFromSearch.text)
}
}
}
And this is the code for the TableViewController that I have set up for the results to be displayed in.
import UIKit
import GoogleBooksApiClient
class SearchResultsTableViewController: UITableViewController {
var titleFromSearch: String?
var authorFromSearch: String?
var data = [Volume]()
override func viewDidLoad() {
super.viewDidLoad()
let session = URLSession.shared
let client = GoogleBooksApiClient(session: session)
let req = GoogleBooksApi.VolumeRequest.List(query: "Google")
let task: URLSessionDataTask = client.invoke(
req,
onSuccess: { [weak self] volumes in
self?.data = volumes.items
self?.tableView.reloadData()
},
onError: { error in
print("\(error)") }
)
task.resume()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection
section: Int) -> Int {
return data.count
}
override func tableView(_ tableView: UITableView, cellForRowAt
indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell",
for: indexPath)
let item = data[indexPath.row]
cell.textLabel?.text = item.volumeInfo.title
cell.detailTextLabel?.text = item.volumeInfo.authors.first
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
if let destination = segue.destination as? ViewController {
destination.delegate = self
}
}
}
Here is where I get the let constant error is with these two assignment statements:
extension SearchResultsTableViewController: ViewControllerDelegate {
func searchInput(_ titleFromSearch: String?, authorFromSearch: String?)
{
titleFromSearch = titleFromSearch
authorFromSearch = authorFromSearch
}
}
I added all the code because as I said I am new to iOS and I'm not sure where this error stems from in the code.
In the two lines causing your errors:
titleFromSearch = titleFromSearch
authorFromSearch = authorFromSearch
you are attempting to assign the parameters to themselves. You want to set the parameter values to your properties of the same name. To do this, add self. to the property references:
self.titleFromSearch = titleFromSearch
self.authorFromSearch = authorFromSearch

UILabel throwing Thread1: EXC_BAD_ACCESS (code=1, address 0x…) in Swift 2

when I would like to make the data from the valise, table view controller (SelectedCity) ,app crash and error : Thread1: EXC_BAD_ACCESS (code=1, address 0x…)
error is in line labelcity!.text = tit varibale tit not problem ,I think the problem lies in the UIlabel (labelcity)
can you help me?
AircraftSearch
class AircraftSearch: UIViewController ,SendbackDelegate{
#IBOutlet weak var Mabda: UIButton!
#IBOutlet weak var maghsad: UIButton!
#IBOutlet weak var labelcity: UILabel!
var Airurl = NSURL()
var ScrOrDstArray = [MabdaAndMaghsad]()
var origin = [String]() // save mabda
var purpose = [String]() // save maghsad
var sendDataToTableview = [String]()
var tit = String()
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
GetPassCity()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func selectMabda(sender: AnyObject) {
sendDataToTableview = origin
performSegueWithIdentifier("SelectedCellSegue", sender: sender)
}
#IBAction func selectMaghsad(sender: AnyObject) {
sendDataToTableview = purpose
print(sendDataToTableview)
performSegueWithIdentifier("SelectedCellSegue", sender: sender)
}
func originAndpurpose() {
let dataCity = ScrOrDstArray
for i in dataCity{
if i.SrcOrDst == true{
origin.append(i.Name)
}else{
purpose.append(i.Name)
}
}
}
func sendNameToPreviousVC(SelectCity: String) {
print("\(tit) selected ") //return data
tit = SelectCity
labelcity!.text = tit
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "SelectedCellSegue" {
if let VC = segue.destinationViewController as? SelectedCity {
VC.toTake = sendDataToTableview
VC.delegate = self
}
}
}
}
SelectedCity view
import UIKit
protocol SendbackDelegate:class {
func sendNameToPreviousVC(City:String)
}
class SelectedCity: UITableViewController {
var toTake = [String]()
var selecteCity = String()
weak var delegate: SendbackDelegate? = nil
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return toTake.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("stcell", forIndexPath: indexPath) as? mAndMCell
let nameCity = toTake[indexPath.row]
print(nameCity)
cell!.nameCityLabel.text = nameCity
return cell!
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
let indexPath = tableView.indexPathForSelectedRow!
let currentCell = tableView.cellForRowAtIndexPath(indexPath) as! mAndMCell!
selecteCity = currentCell.nameCityLabel!.text as String!
sendBackIdCity(selecteCity)
navigationController?.popViewControllerAnimated(true)
}
func sendBackIdCity(name: String){
self.delegate?.sendNameToPreviousVC(name)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "backCitySegue"{
var VCOne = segue.destinationViewController as? AircraftSearch
self.delegate = VCOne
}
}
}
Instead of
#IBOutlet weak var labelcity: UILabel? = UILabel()
try:
#IBOutlet weak var labelcity: UILabel!
Consider to remove weak keyword in the property declaration. Usage of this keyword prevents just created UILabel object from it's retaining, so the object deallocates immediately.
var labelcity: UILabel? = UILabel()
Or another option is to move object instantiation into viewDidLoad method:
var labelcity: UILabel!
...
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel()
//you code for subview adding into view controller's view
labelcity = label
GetPassCity()
}
I solved the problem:
override func viewDidLoad() {
super.viewDidLoad()
labelcity.text = tit
GetPassCity()
}
func sendNameToPreviousVC(SelectCity: String) {
tit = SelectCity
}

How to pass data to AddController to UITableViewController

I have a problem with my swift code. I have an UITableViewCotroller with a prototype cell, in this cell there are three labels. I created the file TimerCell.swift with the #IBOutlet for the labels:
import UIKit
class TimerCell: UITableViewCell {
#IBOutlet var circostanza: UILabel!
#IBOutlet var luogo: UILabel!
#IBOutlet var tempo: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
and the file TimerModel.swift with this code:
import UIKit
class TimerModel: NSObject, NSCoding {
var circostanza :String!
var luogo : String!
var tempo : String!
init(circostanzaIn:String, luogoIn:String, tempoIn:String) {
circostanza = circostanzaIn
luogo = luogoIn
tempo = tempoIn
}
internal required init(coder aDecoder: NSCoder) {
self.circostanza = aDecoder.decodeObjectForKey("circostanza") as! String
self.luogo = aDecoder.decodeObjectForKey("luogo") as! String
self.tempo = aDecoder.decodeObjectForKey("tempo") as! String
}
func encodeWithCoder(encoder: NSCoder) {
encoder.encodeObject(self.circostanza, forKey: "circostanza")
encoder.encodeObject(self.luogo, forKey: "luogo")
encoder.encodeObject(self.tempo, forKey: "tempo")
}
}
Then I have a button + in the UITableViewCotroller to open an AddController with three text field to add some data. I want to save these data in the cell's labels. The code in the AddController is:
import UIKit
class AddTimerController: UIViewController, UITextFieldDelegate {
#IBOutlet var fieldCircostanza: UITextField!
#IBOutlet var fieldLuogo: UITextField!
#IBOutlet var fieldTempo: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
fieldCircostanza.delegate = self
fieldLuogo.delegate = self
//
var keyboardToolbar = UIToolbar(frame: CGRectMake(0, 0, self.view.bounds.size.width, 44))
keyboardToolbar.barStyle = UIBarStyle.BlackTranslucent
keyboardToolbar.backgroundColor = UIColor.redColor()
keyboardToolbar.tintColor = UIColor.whiteColor()
var flex = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
var save = UIBarButtonItem(title: "Fatto", style: UIBarButtonItemStyle.Done, target: fieldTempo, action: "resignFirstResponder")
keyboardToolbar.setItems([flex, save], animated: false)
fieldTempo.inputAccessoryView = keyboardToolbar
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder() // chiudere la tastiera nei campi di testo
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func annulla(sender: UIButton) {
dismissViewControllerAnimated(true, completion: nil) // chiude una modal
}
#IBAction func salva(sender: UIButton) {
if fieldCircostanza.text.isEmpty &&
fieldLuogo.text.isEmpty &&
fieldTempo.text.isEmpty{
//alertView
return
}
var timer = TimerModel(circostanzaIn: fieldCircostanza.text,
luogoIn: fieldLuogo.text,
tempoIn: fieldTempo.text)
DataManager.sharedInstance.salvaArray()
DataManager.sharedInstance.detail.myCollection.reloadData()
dismissViewControllerAnimated(true, completion: nil)
}
}
Finally the UITableViewCotroller file:
import UIKit
class TimerViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return DataManager.sharedInstance.storage.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TimerCell
//cell.circostanza.text = timer.circostanza
//cell.luogo.text = timer.luogo
//cell.tempo.text = timer.tempo
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
DataManager.sharedInstance.storage.removeAtIndex(indexPath.row)
DataManager.sharedInstance.salvaArray()
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
// MARK: - Navigazione
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "modifica" {
//let controller = (segue.destinationViewController as UINavigationController).topViewController as AddController
}
}
}
Can you help me with the code for saving data?
for your query in the comment, this will correct that:
In your TimerModel:
import UIKit
class TimerModel: NSObject, NSCoding {
var circostanza :String!
var luogo : String!
var tempo : String!
override init() { // add this method
super.init()
}
init(circostanzaIn:String, luogoIn:String, tempoIn:String) {
circostanza = circostanzaIn
luogo = luogoIn
tempo = tempoIn
}
internal required init(coder aDecoder: NSCoder) {
self.circostanza = aDecoder.decodeObjectForKey("circostanza") as! String
self.luogo = aDecoder.decodeObjectForKey("luogo") as! String
self.tempo = aDecoder.decodeObjectForKey("tempo") as! String
}
func encodeWithCoder(encoder: NSCoder) {
encoder.encodeObject(self.circostanza, forKey: "circostanza")
encoder.encodeObject(self.luogo, forKey: "luogo")
encoder.encodeObject(self.tempo, forKey: "tempo")
}
}
For accessing timer in tableViewController, do this:
import UIKit
class AddTimerController: UIViewController, UITextFieldDelegate {
#IBOutlet var fieldCircostanza: UITextField!
#IBOutlet var fieldLuogo: UITextField!
#IBOutlet var fieldTempo: UITextField!
var timer: TimerModel! // Made timer a class member
override func viewDidLoad() {
......
}
// your code ....
#IBAction func salva(sender: UIButton) {
if fieldCircostanza.text.isEmpty &&
fieldLuogo.text.isEmpty &&
fieldTempo.text.isEmpty{
//alertView
return
}
timer = TimerModel(circostanzaIn: fieldCircostanza.text, // intialize timer
luogoIn: fieldLuogo.text,
tempoIn: fieldTempo.text)
DataManager.sharedInstance.salvaArray()
DataManager.sharedInstance.detail.myCollection.reloadData()
dismissViewControllerAnimated(true, completion: nil)
}
}
and after that in tableViewController, access it like this:
class TimerViewController: UITableViewController {
var timer: TimerModel! // Change to this
override func viewDidLoad() {
super.viewDidLoad()
var controller : AddTimerController = AddTimerController()
timer = controller.timer
}
// your code .......
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TimerCell
cell.circostanza.text = timer.circostanza
cell.luogo.text = timer.luogo
cell.tempo.text = timer.tempo
return cell
}
}