神刀安全网

Persistent Data with Property List Tutorial

In this tutorial items of an array will be saved from and loaded to a property list. This will keep the data persistent and so when the app will terminate the current data will be available next time the app is started. This tutorial is made with Xcode 7.3.1 and built for iOS 9.3

Open Xcode and create a new Single View Application. For product name, use IOS9PersistentPropertyListTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.

Persistent Data with Property List Tutorial

Remove the View Controller from the Storyboard and drag a Navigation Controller to the empty canvas. The Navigation Controller will automatically put a Table View Controller onto the storyboard. When the initial View Controller is deleted there isn’t a starting point defined. Select the Navigation Controller and go to the Attribute Inspector. In the View Controller Section select the "Is Initial View Controller" checkbox.

Persistent Data with Property List Tutorial

Double-click the Title Bar of the Table View Controller and set the title to "Items". Next, Drag a Bar Button Item to the right side of the Title Bar. Select the Bar Button Item and go to the Attributes inspector. In the Bar Button Item section change the System item to "Add".

Persistent Data with Property List Tutorial

Inside the Table View Controller select the Table View Cell and go to the Attributes Inspector. In the Table View Cell section set the Identifier  to " Cell" .

Persistent Data with Property List Tutorial

The Storyboard should look like this.

Persistent Data with Property List Tutorial

Since we have deleted the View Controller from the Storyboard we can also delete the ViewController.swift file. Add a new file to the project, select iOS->Source->Cocoa Touch Class. Name it TableViewController and make it a subclass of UITableViewController.

Persistent Data with Property List Tutorial

Go to the Storyboard and select the Table View Controller. go to the Identity inspector and in the Custom Class section change the class to TableViewController.

Persistent Data with Property List Tutorial

Go to the TableViewController.swift file and add the following property

var items = ["Item 1", "Item 2", "Item 3"]

Add the delegate and datasource required methods of the Table View Controller.

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {     return 1 }  override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {     return items.count }  override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {     let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)      // Configure the cell...              cell.textLabel?.text = items[indexPath.row]     return cell }

The Table View has one section with three rows containing the data from the items property array. To make use of persistent data the current items needs to be saved. Add the saveData method

func saveData() {     let data = NSMutableData()              // 1     let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)     let path = paths[0]     let file = (path as NSString).stringByAppendingPathComponent("Persistent.plist")              //2     let archiver = NSKeyedArchiver(forWritingWithMutableData: data)     archiver.encodeObject(items, forKey: "items")     archiver.finishEncoding()     data.writeToFile(file, atomically: true) }
  1. The property list will be saved in the Documents directory of the current app
  2. NSKeyedArchiver encodes the items array and writes it to the property list

Next, add the loadData method

func loadData() {     let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)     let path = paths[0]     let file = (path as NSString).stringByAppendingPathComponent("Persistent.plist")              // 1     if NSFileManager.defaultManager().fileExistsAtPath(file) {         if let data = NSData(contentsOfFile: file) {             let unarchiver = NSKeyedUnarchiver(forReadingWithData: data)             items = unarchiver.decodeObjectForKey("items") as! [String]                              unarchiver.finishDecoding()         }     } }
  1. If the property list exists and there is data inside it, NSKEyedUnarchiver decodes the data and puts it in the items array.

The loadData method needs to be called when the app starts, so add this to the viewDidLoad method

override func viewDidLoad() {     super.viewDidLoad()          loadData() }

Open the Assistant Editor and make sure the TableViewController.swift file is visible. Ctrl and drag from the Bar Button Item to the TableViewController class to create the following Action.

Persistent Data with Property List Tutorial

Implement the addItem method

@IBAction func addItem() {     // 1     let newRowIndex = items.count     let item = ("Item /(newRowIndex + 1)")     items.append(item)              // 2     let indexPath = NSIndexPath(forRow: newRowIndex, inSection: 0)     let indexPaths = [indexPath]     tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: .Automatic)              saveData() }
  1. A new item is added to the items array
  2. The item is displayed below the current items in the Table View.

Build and Runthe Project. Initially the 3 items are displayed. Add a few items. Go to Hardware menu and choose Home. This will simulate a press of the home button. The stop the runnign project in Xcode. Next, run the Project again, the new items will be loaded from the persistent list.

Persistent Data with Property List Tutorial

You can download the source code of the IOS9PersistentPropertyListTutorial at the ioscreator repository on Github .

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Persistent Data with Property List Tutorial

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址