如何保存注释



我有我的代码,所以它在地图上放置一个注释,每次用户点击一个按钮,但当用户关闭应用程序,注释消失。如何让注释保持在地图上即使用户关闭了应用程序?下面是我的代码:

import UIKit
import CoreLocation
import MapKit
class UpdateCar: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var lblLocation: UILabel!
var locationManager = CLLocationManager()
var myPosition = CLLocationCoordinate2D()
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    locationManager.delegate = self
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) {
    println("Updating Car Location (newLocation.coordinate.latitude) , (newLocation.coordinate.longitude) ")
    myPosition = newLocation.coordinate
    locationManager.stopUpdatingLocation()
    lblLocation.text = "(newLocation.coordinate.latitude) , (newLocation.coordinate.longitude)"
}
@IBAction func findUserLocationAndDropPin(sender: UIButton) {
    var userLocationCoordinates = CLLocationCoordinate2DMake(locationManager.location.coordinate.latitude, locationManager.location.coordinate.longitude)
    var pinForUserLocation = MKPointAnnotation()
    pinForUserLocation.coordinate = userLocationCoordinates
    mapView.addAnnotation(pinForUserLocation)
    mapView.showAnnotations([pinForUserLocation], animated: true)
    }
}

您必须将其保存在持久存储中。

几个选项:

  • CoreData,原生的数据保存方式,推荐,不要太简单
  • NSUserDefaults,通常被认为是小的东西,也是原生的,不推荐,虽然很容易
  • 另一个用于管理持久存储的API,如Realm(类似于CoreData,稍微容易一些,但不是本机)
//when I need to save for example, the last date on which the user login my app will use the setObject function, this will save a value ("10/05/2015") in the "lastlogin" key
var lastLogin = "10/05/2015"
NSUserDefaults.standarUserDefaults().setObject(lastLogin, forkey: "lastLogin")
//And when I need to retrieve the stored value in the "lastlogin" key which I use is "objectForKey" function
NSUserDefaults.standarUserDefaults().objectForKey("lastLogin")

见以下链接:https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/index.html//apple_ref/occ instm/NSUserDefaults/setObject: forKey:

最新更新