我通过搜索栏在地图上放置了图钉,并检索了它的坐标,并将其保存在myLatitude和myLongitude的两倍中。这是在以下代码片段中完成的:
class1.h
@interface Location : UIViewController <UISearchBarDelegate, MKMapViewDelegate>
@property (nonatomic, readwrite) double myLatitude;
@property (nonatomic, readwrite) double myLongitude;
class1.m
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[self.mySearch resignFirstResponder];
//geoloc
CLGeocoder *geocoder = [[CLGeocoder alloc]init];
[geocoder geocodeAddressString:self.mySearch.text completionHandler:^(NSArray *placemarks, NSError *error)
{
//mark location and center
CLPlacemark *placemark = [placemarks objectAtIndex:0];
MKCoordinateRegion region;
CLLocationCoordinate2D newLocation = [placemark.location coordinate];
region.center = [(CLCircularRegion *)placemark.region center];
//drop pin
MKPointAnnotation *annotation = [[MKPointAnnotation alloc]init];
[annotation setCoordinate:newLocation];
[annotation setTitle:self.mySearch.text];
[self.mapView addAnnotation:annotation];
//scroll to search result
MKMapRect mr = [self.mapView visibleMapRect];
MKMapPoint pt = MKMapPointForCoordinate([annotation coordinate]);
mr.origin.x = pt.x - mr.size.width *0.5;
mr.origin.y = pt.y - mr.size.height *0.25;
[self.mapView setVisibleMapRect:mr animated:YES];
myLatitude = newLocation.latitude;
myLongitude = newLocation.longitude;
NSLog(@"lat: %f, long: %f", myLatitude, myLongitude);
}];
}
现在,我想在不同的class2中使用这些双精度数(myLatitude和myLongitude),换句话说,我需要这两个双精度数是全局的,如何使它们成为全局的,然后又如何在class2中称呼它们?任何代码将不胜感激!
最简单的方法可能是使用单例。
您可以创建一个新的单例类,然后可以从您应用程序中的任何位置进行访问。因此,您可以创建CoordinateManager
或其他内容,然后使用它来处理要成为全局位置坐标。
例如 CoordinateManager.h
@interface CoordinateManager : NSObject
+ (CoordinateManager *)sharedManager;
@property float latitiude;
@property float longitude;
@end
和 CoordinateManager.m
@implementation CoordinateManager
@synthesize latitiude;
@synthesize longitude;
static CoordinateManager *manager = nil;
+ (CoordinateManager *)sharedManager
{
if (manager) {
return manager;
}
else {
@synchronized(self) {
if (!manager) {
manager = [[CoordinateManager alloc] init];
}
return manager;
}
}
}
@end
然后,您将设置以下属性:
[[CoordinateManager sharedManager] setLatitude:1.067594];
只要您导入,就可以从应用程序中的任何位置进行访问CoordinateManager.h
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句