情况一:地理编码
storyboard:
代码如下(项目并未导入MapKit框架,但运行程序并不崩溃):
1 #import "ViewController.h" 2 #import <CoreLocation/CoreLocation.h> 3 4 @interface ViewController () 5 @property (weak, nonatomic) IBOutlet UITextField *addressTF; 6 @property (weak, nonatomic) IBOutlet UILabel *longitudeLabel; 7 @property (weak, nonatomic) IBOutlet UILabel *latitudeLabel; 8 @property (weak, nonatomic) IBOutlet UILabel *detailLabel; 9 10 @end 11 12 @implementation ViewController 13 14 - (void)viewDidLoad { 15 [super viewDidLoad]; 16 // Do any additional setup after loading the view, typically from a nib. 17 } 18 19 //地理编码 20 - (IBAction)geocode { 21 //创建地理编码对象 22 CLGeocoder * geocoder = [[CLGeocoder alloc]init]; 23 24 if (self.addressTF.text == nil) { 25 return ; 26 } 27 28 [geocoder geocodeAddressString:self.addressTF.text completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) { 29 if (error) { 30 NSLog(@"%@",error); 31 return ; 32 } 33 //获取地标 CLPlacemark 34 for (CLPlacemark * placemark in placemarks) { 35 self.longitudeLabel.text = [NSString stringWithFormat:@"%f",placemark.location.coordinate.longitude]; 36 self.latitudeLabel.text = [NSString stringWithFormat:@"%f",placemark.location.coordinate.latitude]; 37 self.detailLabel.text = placemark.name;//具体地名 38 NSLog(@"%@",placemark.locality);//城市名 39 } 40 41 }]; 42 43 44 } 45 46 @end
情况二:添加地图View
storyboard:
代码(项目没有导入框架,但程序崩溃):
1 #import "ViewController.h" 2 #import <MapKit/MapKit.h> 3 4 @interface ViewController () 5 6 @end 7 8 @implementation ViewController 9 10 - (void)viewDidLoad { 11 [super viewDidLoad]; 12 // Do any additional setup after loading the view, typically from a nib. 13 } 14 15 16 - (void)didReceiveMemoryWarning { 17 [super didReceiveMemoryWarning]; 18 // Dispose of any resources that can be recreated. 19 } 20 21 22 @end
程序崩溃报错:
*** Terminating app due to uncaught exception ‘NSInvalidUnarchiveOperationException‘, reason: ‘Could not instantiate class named MKMapView‘
导入MapKit框架后,则能成功运行.
为什么有的时候崩溃而有的时候不会?
因为在XCode5之后,在你#import <MapKit/MapKit.h>之后,程序默认帮助程序员导入框架.但由于情景二中程序运行后,先走的是storyboard中箭头指向的控制器,发现有MKMapView控件,而程序那时候还没有自动导入框架,所以崩溃. 而情景一中,storyboard中的控件并没有涉及到任何相关的控件,而是在代码中导入了头文件之后才使用了CoreLocation相关的方法,那个时候程序已经自动帮我们导入了框架,所以不会崩溃.
所以,只要在storyboard的中使用了UIKit之外的框架,必须手动在项目中导入.
不导入框架为什么有时崩溃有时不崩溃
时间: 2024-10-23 11:39:11