Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Simple To Do App in Swift 2 and Xcode 7

Hi,

I am practicing my Swift and I hit a bump. I am making simple to do app, and it works but I want to upgrade it with persistence with NSUserDefaults

So here is my code which need refactoring... I know...

import UIKit

var listItems = [String]()

class SecondViewController: UIViewController {

    @IBOutlet weak var userInput: UITextField!

    @IBAction func addItem() {
        if userInput.text?.characters.count > 0 {
            listItems.append(userInput.text!)
            userInput.text = ""
            self.view.endEditing(true)
            print(listItems)
        }

    }    

    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.
    }


}

How to add this functionality, I really don't understand.

One more thing. This part is bad. How to make optional binding with UITextField object?

@IBAction func addItem() {
        if userInput.text?.characters.count > 0 {
            listItems.append(userInput.text!)
            userInput.text = ""
            self.view.endEditing(true)
            print(listItems)
        }

    }

2 Answers

Jari Koopman
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Jari Koopman
Python Web Development Techdegree Graduate 29,349 Points

Hi Antonija,

I can't help you with refactoring your code. But creating an NSUserdefault can be done by the following code:

let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

To add an object:

defaults.setObject(objectName, forKey: "key")

To reach the object:

print(defaults.dataForKey("key"))

I hope you can go on with your project!

Thanks, I somehow managed to do this alone.