Swift 2.2, RealmSwift - Retrieval of data not working - ios

I am using realm for my notepad app to store the array noteTitles, which is of a custom class Note. The app works fine, but when it is supposed to save, it doesn't pass through. When I restart the app, the notes are gone. I will give code to all of the files. Also, I want the user to add notes and I need the ObjectForPrimaryKey to update everytime so a new id is created for each note.
Note Class Code:
import Foundation
import RealmSwift
class Note: Object {
dynamic var title = ""
var content = ""
var id = 0
override class func primaryKey() -> String? {
print("id generated")
return "id"
}
}
ViewController(Where I write the notes) Code:
import UIKit
import RealmSwift
var note2 = Note()
var note: Note!
let realm = try! Realm()
class ViewController3: UIViewController, UITextViewDelegate {
var note: Note!
#IBOutlet var noteText: UITextView!
#IBOutlet var noteTitle: UITextField!
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
noteTitle.text = note.title
noteText.text = note.content
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
note.title = noteTitle.text!
note.content = noteText.text
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textViewDidEndEditing(textView: UITextView) {
func noteEnded(note2: Note) {
note2.title = note.title
note2.content = note.content
note2.id = note.id
do {
try realm.write {
realm.add(noteTitles, update: true)
print("added")
}
} catch {
print("There was a problem")
}
}
print("editing ended")
}
override func viewDidLoad() {
super.viewDidLoad()
print(note2.id)
self.noteText.delegate = self
// Do any additional setup after loading the view.
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
noteTitle.resignFirstResponder()
noteText.resignFirstResponder()
}
}
TableViewController(Note List) Code:
import UIKit
import RealmSwift
var noteTitles:[Note] = []
class TableViewController: UITableViewController {
// 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 noteTitles.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel!.text = noteTitles[indexPath.row].title // error here
// Configure the cell...
return cell
}
override func viewDidAppear(animated: Bool) {
tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
sleep(2)
if realm.objectForPrimaryKey(Note.self, key: 0) != nil {
realm.objectForPrimaryKey(Note.self, key: 0)
}
// 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()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
noteTitles.removeAtIndex(indexPath.row)
tableView.reloadData()
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier! == "editNote" {
let noteDetailViewController = segue.destinationViewController as! ViewController3
let selectedIndexPath = tableView.indexPathForSelectedRow
noteDetailViewController.note = noteTitles[selectedIndexPath!.row]
} else if segue.identifier! == "addNote" {
let note = Note()
noteTitles.append(note)
let noteDetailViewController = segue.destinationViewController as! ViewController3
noteDetailViewController.note = note
}
}
}
Thanks in advance!

The function noteEnded should not inside the textViewDidEndEditing and it is not being called.
Try this
func noteEnded(note2: Note) {
do {
try realm.write {
realm.add(note2, update: true)
print("added")
}
} catch {
print("There was a problem")
}
}
func textViewDidEndEditing(textView: UITextView) {
note2.title = note.title
note2.content = note.content
note2.id = note.id
noteEnded(note2)
print("editing ended")
}
It is also better to have "Done" button to save the note. Easy to handle the input and save.

Related

Sending data of UISwitch from one view controller to another?

I am 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. So while coding I had a set of questions so it would be really helpful if you can help me.
Question 1: I have used UISwitch to know if user owes or the other person owes. So, depending on switch on and off the amount will have negative value if user owes and positive if other person owes. Also, the value is shown on other viewcontroller so how do I pass the state of UISwitch and how do I make the value negative and positive depending on the UISwitch's result?
Question 2: I want to show the balance(So the owes of user to that person would sum up and display) of the user in the title of Navigation Controller so how do it?
ViewControllers:
NewOwedDetailViewController: This is where I store new owe details of the person
Code:
import UIKit
class NewOwedDetailViewController: UIViewController {
#IBOutlet weak var titleTextField: UITextField!
#IBOutlet weak var locationTextField: UITextField!
#IBOutlet weak var amountTextField: UITextField!
#IBOutlet weak var datePicker: UIDatePicker!
var person: People?
var owe: Owe?
override func viewDidLoad() {
super.viewDidLoad()
titleTextField.delegate = self as UITextFieldDelegate
locationTextField.delegate = self as UITextFieldDelegate
amountTextField.delegate = self as UITextFieldDelegate
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
titleTextField.resignFirstResponder()
locationTextField.resignFirstResponder()
amountTextField.resignFirstResponder()
}
#IBAction func saveOwe(_ sender: Any) {
let name = titleTextField.text
let location = locationTextField.text
let amountText = amountTextField.text ?? ""
let amount = Double(amountText) ?? 0.0
let date = datePicker.date
if let owe = Owe(name: name, location: location, amount: amount, date: date) {
person?.addToRawOwes(owe)
//Below try function code has save() as throw function so whenever throw function are there you just add try at the beggining of the function
do {
try owe.managedObjectContext?.save()
self.navigationController?.popViewController(animated: true)
} catch {
print("Owe details could not be created")
}
}
}
#IBAction func oweSwitch(_ sender: UISwitch) {
if sender.isOn {
owe?.amount = (owe?.amount)! * (-1)
} else {
owe?.amount = (owe?.amount)! * (1)
}
}
}
extension NewOwedDetailViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return true
}
}
PersonDetailsTableViewController: This is where I display all details of that particular person's owe history
import UIKit
import ChameleonFramework
class PersonDetailsTableViewController: UITableViewController {
#IBOutlet weak var personDetailsTableView: UITableView!
let dateFormatter = DateFormatter()
var person: People?
override func viewDidLoad() {
super.viewDidLoad()
dateFormatter.timeStyle = .long
dateFormatter.dateStyle = .long
}
override func viewWillAppear(_ animated: Bool) {
self.personDetailsTableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func addNewOwe(_ sender: Any) {
performSegue(withIdentifier: "addOweDetails", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let destination = segue.destination as? NewOwedDetailViewController else {
return
}
destination.person = person
}
func deleteOwe(at indexPath: IndexPath) {
guard let owe = person?.owe?[indexPath.row],
let managedContext = owe.managedObjectContext else {
return
}
managedContext.delete(owe)
do {
try managedContext.save()
personDetailsTableView.deleteRows(at: [indexPath], with: .automatic)
} catch {
print("Could not delete owes")
personDetailsTableView.reloadRows(at: [indexPath], with: .automatic)
}
}
}
extension PersonDetailsTableViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return person?.owe?.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = personDetailsTableView.dequeueReusableCell(withIdentifier: "detailsCell", for: indexPath)
if let owe = person?.owe?[indexPath.row] {
cell.textLabel?.text = owe.name
if let amount = person?.owe?[indexPath.row] {
cell.detailTextLabel?.text = "₹ \(owe.amount)"
}
}
return cell
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
deleteOwe(at: indexPath)
}
}
}
extension PersonDetailsTableViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "addOweDetails", sender: self)
}
}
Screen
PersonDetailsTableViewController
NewOwedDetailViewController

Delegate between controllers doesn't work. Why?

I try to use delegate to send data from textField which is in the Detail2(ViewController) to array which is in the ViewController.
I used here print method and first print show that one element has been added to the array but the second print method which is below the ViewVillAppear() show that array is empty. How? I want to be able to to use delegate to add data to my table.
["sdsd"] First print from the console
[]Second print from the console
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet var add: UIBarButtonItem!
#IBOutlet var tv: UITableView!
var array :[String] = []
override func viewDidLoad() {
super.viewDidLoad()
tv.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segue" {
let vc: Detail2 = segue.destination as! Detail2
vc.delegate = self
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return array.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = array[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
array.remove(at: indexPath.row )
tv.reloadData()
}
}
func alert () {
}
override func viewWillAppear(_ animated: Bool) {
tv.reloadData()
print(array)
}
}
extension ViewController: Data {
func tekst(data: String) {
array.append(data)
print(array)
}
}
and Detail2
protocol Data {
func tekst (data: String)
}
class Detail2: UIViewController {
var delegate: Data? = nil
#IBAction func btn(_ sender: Any) {
let sb = storyboard?.instantiateViewController(withIdentifier: "Main" ) as! ViewController
navigationController?.pushViewController(sb, animated: true)
if delegate != nil {
if txtfield.text != nil {
let napis = txtfield.text
delegate?.tekst(data: napis!)
}
}
}
#IBOutlet var btn: UIButton!
#IBOutlet var txtfield: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
btn.backgroundColor = UIColor.blue
btn.tintColor = UIColor.white
btn.layer.cornerRadius = 25
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Just update your function with:
#IBAction func btn(_ sender: Any) {
if delegate != nil {
if txtfield.text != nil {
let napis = txtfield.text
delegate?.tekst(data: napis!)
}
navigationController?.popViewController(animated: true)
}
}
Update:
extension ViewController: Data {
func tekst(data: String) {
array.append(data)
print(array)
self.tv.reloadData()
}
}
You need to add this delegate?.tekst(data: napis!) inside completion handler, because you are using navigationController, there is no option for completion handler,So have to add UINavigationController extension like that:
extension UINavigationController {
public func pushViewController(viewController: UIViewController,
animated: Bool,
completion: (() -> Void)?) {
CATransaction.begin()
CATransaction.setCompletionBlock(completion)
pushViewController(viewController, animated: animated)
CATransaction.commit()
}
}
change this
navigationController?.pushViewController(sb, animated: true){
if delegate != nil {
if txtfield.text != nil {
let napis = txtfield.text
delegate?.tekst(data: napis!)
}
Update your code in Detail2 viewcontroller
#IBAction func btn(_ sender: Any) {
if delegate != nil {
if txtfield.text != nil {
let napis = txtfield.text
delegate?.tekst(data: napis!)
}
}
navigationController?.popViewController(animated: true)
}
In the ViewController implement the delegate method
func tekst (data: String) {
array.append(data)
}
// in detail
#IBAction func btn(_ sender: Any) {
if txtfield.text != nil {
let napis = txtfield.text
delegate?.tekst(data: napis!)
}
/// dismiss detail here don't push main again
self.navigationController?.popViewController(animated: true)
}

Swift 2 Nil Delegate

So I want to create a IOS application that generates a group of students, adds them to a course and then shows students. I can show students in a list in a table view but now I want to let the user touch a student's name and be taken to a page with information about that student (name highest grade etc). The student class is flawless, the course works and the only problem I have is that I can't get a student from one view to the other.
Here's what I have so far:
//
// DataTableViewController.swift
// assignment8
//
import Foundation
import UIKit
class DataTableViewController: UITableViewController {
var delegate:StudentSelectionDelegate! = nil
var students = [Student]();
var course = Course();
// MARK: - UITableViewDataSource
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
func didSelectStudent(controller:UITableViewController, student:Student!) {
controller.navigationController?.popViewControllerAnimated(true)
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
self.course = courseStorage.getCourse();
self.students = course.getArrayOfStudentSortedByLastName();
return course.count;
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let row = indexPath.row
let currentStudent = students[row];
if (delegate != nil) {
delegate.didSelectStudent(self,student:currentStudent)
}
else {
print ("delegate is nil :(");
}
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("studentCell", forIndexPath: indexPath)
cell.textLabel?.text = students[indexPath.row].lastName + ", " +
students[indexPath.row].firstName;
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
print("ping");
if segue.identifier == "studentSegue" {
let nextScene = segue.destinationViewController as! studentViewController
// Pass the selected object to the new view controller.
if let indexPath = self.tableView.indexPathForSelectedRow {
let selectedStudent = students[indexPath.row]
print (selectedStudent.firstName);
nextScene.student = selectedStudent;
}
}
}
}
and
//
// DataViewController.swift
// assignment8
//
import UIKit
class DataViewController: UIViewController {
#IBOutlet weak var dataLabel: UILabel!
var dataObject: String = ""
let tableData = ["One","Two","Three"];
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.dataLabel!.text = dataObject
}
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int)
-> Int {
return self.tableData.count;
}
}
and
//
// studentViewController.swift
// assignment8
//
import UIKit
protocol StudentSelectionDelegate {
func didSelectStudent(controller: UITableViewController, student:Student)
}
class studentViewController: UIViewController {
var delegate = StudentSelectionDelegate.self;
var name = String();
var student = Student();
#IBOutlet weak var StudentName: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func didSelectStudent(controller:UITableViewController, student:Student!) {
student.description;
print ("pong")
StudentName.text = student.firstName + " " + student.lastName;
controller.navigationController?.popViewControllerAnimated(true);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// override func viewWillAppear(animated: Bool) {
// StudentName.text = name
// }
}
This is my storyboard so far.
So, any time I try clicking a student it will print the message that I've decided to use if the delegate is nil. So far I've tried looking at all the other answers on SO but none of them have fixed my issue.
To be able to send information from one view controller to another you should use segues. It seems like that's what you're doing according to the image. If you don't know how to use a segue, you can find a good answer here: Sending data with Segue with Swift
With segues you'll be able to set the delegate of the next view controller:
protocol MyDelegate {
func myFunction()
}
class FirstViewController: UIViewController, MyDelegate {
func myFunction() {
// do what the function does
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let secondVC = segue.destinationViewController as? SecondViewController {
secondVC.delegate = self
}
}
}
class SecondViewController: UIViewController {
var delegate: MyDelegate!
}
Before you segue to the second view controller (you're preparing for the segue), you set the delegate variable of SecondViewController to self, because FirstViewController conforms to MyDelegate protocol so it can be used there. Now, in SecondViewController you can use delegate.myFunction() and it will do whatever is written inside the FirstVC's function, because the FirstVC is SecondVC's delegate.

Adding things to NSUserDefaults - multiple views

I am creating a dictionary-like app and I want to store the user's search history using NSUserDefaults. I created a seaechHistory array outside the class. Now I am appending the searchHistory array and save it using NSUserDefaults in willSelectRowAtIndexPath, and I retrieve the stored history in a history view. The storage worked fine but when I re-run the app the NSUserDefaults set the seachHistory to the empty array and thus I lost all the saved data. The synchronize() method does work anywhere.
Initial View Controller:
import UIKit
var searchHistory = [String]()
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {
#IBOutlet weak var tableView: UITableView!
#IBOutlet var textField: UITextField!
#IBAction func textFieldDidChange(sender: AnyObject) {
tableView.hidden = false
searchManager.updateFilter(textField.text)
tableView.reloadData()
}
#IBAction func tapOnTextField(sender: AnyObject) {
let textFieldLength = count(textField.text)
if textFieldLength == 0 {
tableView.hidden = true
} else {
tableView.hidden = false
}
}
override func viewDidLoad() {
super.viewDidLoad()
textField.backgroundColor = UIColor.whiteColor()
tableView.hidden = true
self.textField.delegate = self
}
var searchManager = SearchManager()
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return searchManager.filteredURLCount()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
cell.textLabel!.text = searchManager.filteredURLAtIndex(indexPath.row)
return cell
}
func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
self.textField.text = searchManager.filteredURLAtIndex(indexPath.row)
searchHistory.append(textField.text)
NSUserDefaults.standardUserDefaults().setObject(searchHistory, forKey: "History")
self.performSegueWithIdentifier("cellTapped", sender: "Cell")
textField.text = nil
tableView.hidden = true
textField.resignFirstResponder()
return indexPath
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
self.view.endEditing(true)
self.tableView.hidden = true
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "cellTapped" {
var DestViewController: definitionView = segue.destinationViewController as! definitionView
DestViewController.searchWord = textField.text
}
}
}
History View Controller:
import UIKit
class historyView: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
searchHistory = NSUserDefaults.standardUserDefaults().objectForKey("History")! as! [String]
println(searchHistory)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var destination: ViewController = segue.destinationViewController as! ViewController
}
}
You can read your array in viewDidLoad() method, then it won't be empty.
Add tihs code in your ViewController:
override func viewDidLoad() {
super.viewDidLoad()
searchHistory = NSUserDefaults.standardUserDefaults().objectForKey("History")! as! [String]
}
It should work.

Cannot invoke 'append' with an argument list of type'(String)' in my firstViewController

firstViewController. This is where the problem is. In my 'for loop' it is giving me an error. I have tried to use what Xcode suggested, but it isn't working. I still consider myself a beginner with Swift. I looked at other answers when people have posted the same question and I still can't solve my problem.
import UIKit
var toDoItems:[String] = []
class FirstViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet var tasksTable:UITableView?
override func viewDidLoad() {
super.viewDidLoad()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return toDoItems.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")
cell.textLabel?.text = toDoItems[indexPath.row]
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
if var storedToDoItems : AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey("toDoItems") {
toDoItems = []
for var i = 0; i < storedToDoItems?.count(); ++i {
toDoItems.append(storedToDoItems[i] as! String)
}
}
tasksTable?.reloadData()
}
}
This is my secondViewController.
import UIKit
class SecondViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var toDoItem: UITextField!
#IBAction func addItemButton(sender: AnyObject) {
toDoItems.append(toDoItem.text)
let fixedToDoItems = toDoItems
NSUserDefaults.standardUserDefaults().setObject(fixedToDoItems, forKey: "todDoItems")
NSUserDefaults.standardUserDefaults().synchronize()
self.view.endEditing(true)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
self.view.endEditing(true)
}
}
When you load your to-do list array from NSUserDefaults, use if let to test if it's a [String] (that is, an array of strings), and then you won't need to cast it to a String later on, which might be contributing to your error. Try replacing your viewWillAppear method with this:
override func viewWillAppear(animated: Bool) {
if let storedToDoItems = NSUserDefaults.standardUserDefaults().objectForKey("toDoItems") as? [String] {
toDoItems = []
for var i = 0; i < storedToDoItems.count; ++i {
toDoItems.append(storedToDoItems[i])
}
}
tasksTable?.reloadData()
}
While you're at it, there's a much nicer way to loop over the contents of an array in Swift (and many other languages):
override func viewWillAppear(animated: Bool) {
if let storedToDoItems = NSUserDefaults.standardUserDefaults().objectForKey("toDoItems") as? [String] {
toDoItems = []
for item in storedToDoItems {
toDoItems.append(item)
}
}
tasksTable?.reloadData()
}
In this case however, you should be able to just set your variable directly from the loaded one:
override func viewWillAppear(animated: Bool) {
if let storedToDoItems = NSUserDefaults.standardUserDefaults().objectForKey("toDoItems") as? [String] {
toDoItems = storedToDoItems
}
tasksTable?.reloadData()
}

Resources