How do I save edits to a TextView?

I am very close to completing my first app - a table view app with a detail view.

The detail view has a UITextView that is editable. The editing works and I have been able to save those edits to the current session. However I am missing something that persists the data after the app is closed out. I am using NSCoding in the data model file.

Here is the code from that file:

import UIKit
import os.log

class Season: NSObject, NSCoding {
  var season: Season?
  //MARK: Properties
  var name: String
  var detail: String

  //MARK: Archiving Paths
  static let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
  static let ArchiveURL = DocumentsDirectory.appendingPathComponent("seasons")
  //MARK: Types
  struct PropertyKey {
    static let name = "name"
    static let detail = "detail"

  //MARK: Initialization
  init?(name: String, detail: String) {
    guard !name.isEmpty else {
      return nil
    guard !detail.isEmpty else {
      return nil
    if name.isEmpty || detail.isEmpty {
      return nil
    // Initialize stored properties = name
    self.detail = detail

  //MARK: NSCoding
  func encode(with aCoder: NSCoder) {
    aCoder.encode(name, forKey:
    aCoder.encode(detail, forKey: PropertyKey.detail)
  required convenience init?(coder aDecoder: NSCoder) {
    // the name is required. If we cannnot get a name string, the initializer should fail.
    guard let name = aDecoder.decodeObject(forKey: as? String
      else {
      os_log("Unable to decode the name for a Season object.", log: OSLog.default, type: .debug)
      return nil
    let detail = aDecoder.decodeObject(forKey: PropertyKey.detail)
    self.init(name: name, detail: detail as! String)

Any guidance in saving the edits would be greatly appreciated.


@rouviere Thanks very much for your question! If you’re using the NSCoding protocol, then the logical thing would be to save your data to NSUserDefaults. If all you’re saving is text, then this should suffice.

I hope this helps!

All the best!

Thank you for taking the time to respond to my question. As this is my first app and I am not totally familiar with the process you mention, would you mind pointing me in the direction of a tutorial or something similar that might help?

Thank you.

@rouviere My apologies for the delayed response. Here is a link that you might find useful which shows you how to use NSUserDefaults in Objective-C, and here is an example of how to use it in Swift.

I hope this helps!

All the best!

This topic was automatically closed after 166 days. New replies are no longer allowed.