出乎意料地发现Nil展开了一个Optional值

时间:2016-05-03 06:02:48

标签: ios swift google-maps gmsmapview

我知道还有很多其他问题,但我向你保证,就我所知,这并不重复。正如您在下面的代码中看到的那样,我没有将任何值标记为Optional,但是我一直收到此错误。当我运行snapNext值突出显示

时,它会崩溃
 viewMap.camera = newLocation

以下是完整的代码,我将viewMap链接到常规的UIView

import UIKit
import MapKit
import GoogleMaps

class ViewController: UIViewController {

var camera = GMSCameraPosition.cameraWithLatitude(33.600727, longitude: -117.900840, zoom: 16.9)
@IBOutlet weak var viewMap: GMSMapView!
override func viewDidLoad() {
    super.viewDidLoad()


    viewMap.camera = camera
    viewMap = GMSMapView.mapWithFrame(CGRectZero, camera: camera)
    viewMap.myLocationEnabled = true
    viewMap.settings.myLocationButton = true


    let marker = GMSMarker()
    marker.position = CLLocationCoordinate2DMake(33.600727, -117.900840)
    marker.title = "Newport Beach"
    marker.snippet = "California"
    marker.map = viewMap

    // Do any additional setup after loading the view, typically from a nib.
}

@IBAction func snapNext(sender: AnyObject) {
    let newLocation = GMSCameraPosition.cameraWithLatitude(33.622578, longitude: -117.911099, zoom: 16.9)
    viewMap.camera = newLocation

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


}

3 个答案:

答案 0 :(得分:1)

您的错误就在行中:

viewMap = GMSMapView.mapWithFrame(CGRectZero, camera: camera)

在这里,您要将地图设置为新的匿名对象,并且因为map属性很弱,所以一旦匿名对象超出范围(即nil时,它将自动设置为viewDidLoad完成)。 您要么在故事板中创建对象;在这种情况下,将其作为一个弱的出口,或者你只是想把它作为一个“正常”的财产;在这种情况下,请删除weakIBOutlet

答案 1 :(得分:0)

import UIKit
import MapKit
import GoogleMaps

class ViewController: UIViewControllerGMSMapViewDelegate , CLLocationManagerDelegate {

var camera:GMSCameraPosition!

@IBOutlet weak var viewMap: GMSMapView!
override func viewDidLoad() {
    super.viewDidLoad()

    camera = GMSCameraPosition.cameraWithLatitude(33.600727, longitude: -117.900840, zoom: 16.9)

    viewMap.camera = camera
    viewMap = GMSMapView.mapWithFrame(CGRectZero, camera: camera)
    viewMap.myLocationEnabled = true
    viewMap.delegate=self

    viewMap.settings.myLocationButton = true


    let marker = GMSMarker()
    marker.position = CLLocationCoordinate2DMake(33.600727, -117.900840)
    marker.title = "Newport Beach"
    marker.snippet = "California"
    marker.map = viewMap

    // Do any additional setup after loading the view, typically from a nib.
}

@IBAction func snapNext(sender: AnyObject) {
    camera = GMSCameraPosition.cameraWithLatitude(33.622578, longitude: -117.911099, zoom: 16.9)
    viewMap.camera = camera

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


}

答案 2 :(得分:0)

正如您已经指出的那样viewMap是零。为什么它会被释放,我不知道(需要更多信息才能知道)。但我知道您可以通过删除weak关键字来阻止它。

@IBOutlet weak var viewMap: GMSMapView!

但是,如果在viewMap和视图控制器之间保留周期,则可能会导致泄漏。