首页 > 解决方案 > 在视图之间传输数据,保存在 UserDefaults

问题描述

我的应用程序出现问题,我的标签 (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.
}
*/

}

标签: swiftxcode

解决方案


例如:您可以firstDataPassed选择一个,然后按以下方式进行分配:

nameLabel.text = firstDataPassed ?? name!

如果firstDataPassed为 nil,name!将用于文本。如果name!崩溃,您知道默认值是错误的。

您也可以检查是否为firstDataPassed空字符串,但如果其他 viewController 设置firstDataPassed是否应该使用它,则没有必要。


推荐阅读