我尝试了很多解决方案,但即使在实际设备中,内存消耗也非常高。当第二次观看第一次被解雇时,记忆不会像它的增加那样减少。取消第二次查看后的内存使用量取决于用户在地图中发现的区域数量。 这是我的代码。
第一个视图控制器
import UIKit
import CoreLocation
class ViewController: UIViewController {
let manager = CLLocationManager()
private let currentColor = UIColor(red: 234/255.0, green: 128/255.0, blue: 16/255.0, alpha: 1.0)
override func viewDidLoad(){
super.viewDidLoad()
manager.requestWhenInUseAuthorization()
let button = buttonLoader(y: 7*self.view.frame.height/16, text: "trigger")
self.view.addSubview(button)
}
private func buttonLoader(y:CGFloat,text:String)->UIButton{
let Label = UIButton(frame: CGRect(x: 0, y: y , width: self.view.frame.width, height: self.view.frame.height/8))
Label.setTitle(text, for: .normal)
Label.addTarget(self, action: #selector(mapOpener), for: .touchUpInside)
Label.setTitleColor(currentColor, for: .normal)
self.view.addSubview(Label)
return Label
}
@objc func mapOpener(){
let newView = SecondViewController()
newView.view.backgroundColor = .white
self.present(newView, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
SecondViewController
import UIKit
import MapKit
class SecondViewController: UIViewController {
var map :MKMapView!
var saverButton : UIButton!
override func viewDidLoad() {
super.viewDidLoad()
saveButtonLoader()
mapLoader()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func mapLoader(){
map = MKMapView(frame: CGRect(x: 0, y: 64, width: view.frame.size.width, height: self.view.frame.size.height-64))
map.mapType = MKMapType.standard
map.isZoomEnabled = true
map.isScrollEnabled = true
map.showsUserLocation = true
map.userTrackingMode = .follow
view.addSubview(map)
}
func saveButtonLoader() {
saverButton = UIButton(frame: CGRect(x: 4*view.frame.size.width/5, y: 20, width: view.frame.size.width/5, height: 44))
saverButton.setTitle("Finish", for: .normal)
saverButton.addTarget(self, action: #selector(finishButtonAction), for: UIControlEvents.touchUpInside)
saverButton.backgroundColor = UIColor.blue
saverButton.isEnabled = true
self.view.addSubview(saverButton)
}
override func viewWillDisappear(_ animated:Bool){
super.viewWillDisappear(animated)
self.applyMapViewMemoryFix()
}
func applyMapViewMemoryFix(){
map.delegate = nil
removeOldAnnotations()
map.removeFromSuperview()
map = nil
}
func removeOldAnnotations(){
for annotation in map.annotations{
map.removeAnnotation(annotation)
}
}
@objc func finishButtonAction(sender:UIButton!) {
self.dismiss(animated: true, completion: {
})
}
}