在视图之间传输数据,保存为UserDefaults

时间:2018-08-03 09:01:39

标签: swift xcode

我的应用程序出现问题,我的标签(goalLabel)不会更改为打开应用程序时的目标let(在UserDefaults中设置)。由于某种原因,它将变为null。下面的代码应检查从另一个视图控制器(设置了目标的位置)传输的数据是否等于null。如果不是,则将其更改为goalDataPassed的值,但是如果它等于null(应在应用打开时打开),则应将其更改为userdefaults中保存的任何值。

SecondViewController (标签应该出现的位置):

@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var jobLabel: UILabel!
@IBOutlet weak var goalLabel: UILabel!

@IBOutlet weak var mapView: MKMapView!

var locationManager = CLLocationManager()
var firstDataPassed:String!
var secondDataPassed:String!
var goalDataPassed:String!


let defaults = UserDefaults.standard
let name = UserDefaults.standard.string(forKey: "name")
let job = UserDefaults.standard.string(forKey: "job")
let goal = UserDefaults.standard.string(forKey: "goal")

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view

        nameLabel.text = name
        jobLabel.text = job
        goalLabel.text = goal

    if (firstDataPassed != "") {
        nameLabel.text = firstDataPassed
    }
    if (secondDataPassed != "") {
        jobLabel.text = secondDataPassed
    }
    if (goalDataPassed != "") {
        goalLabel.text = goalDataPassed
    }

    self.locationManager.requestWhenInUseAuthorization()

    if CLLocationManager.locationServicesEnabled() {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        locationManager.startUpdatingLocation()
    }

    let initialLocation = CLLocation(latitude: -34.9285, longitude: 138.6007)

    let regionRadius: CLLocationDistance = 20000
    func centerMapOnLocation(location: CLLocation) {
        let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, regionRadius, regionRadius)
        mapView.setRegion(coordinateRegion, animated: true)
    }
    centerMapOnLocation(location: initialLocation)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let userLocation = locations.last
    let viewRegion = MKCoordinateRegionMakeWithDistance((userLocation?.coordinate)!, 10000, 10000)
    self.mapView.setRegion(viewRegion, animated: true)
}

/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

}

1 个答案:

答案 0 :(得分:1)

例如:您可以将firstDataPassed设为可选,然后按以下方式进行分配:

nameLabel.text = firstDataPassed ?? name!

如果firstDataPassed为零,则将name!用于文本。而且如果name!崩溃了,您就会知道默认值是错误的。

您还可以检查firstDataPassed是否为空字符串,但是如果另一个viewController设置了firstDataPassed是否应使用,则没有必要。