я беру местоположение пользователя с этим кодом:Как я могу использовать местоположение, которое находится в другом классе?
@implementation TabBar
CLLocationManager *locationManager;
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
// NSLog(@"didUpdateToLocation: %@", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
UsersCurrentLongitude = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
UsersCurrentLatitude = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
NSLog(@"Latitude:%@,Longitude:%@",UsersCurrentLatitude,UsersCurrentLongitude);
}
и в NSLog экране она успешно показывает местоположение. но когда я хочу использовать эти местоположения в другом классе, который импортировал мой класс местоположения (в данном случае это TabBar), местоположение становится нулевым. что я могу сделать, чтобы решить эту проблему? Отредактировано:
После того как я попробовать два различных метода для моего вопроса я все еще получаю нуль в NSLog:
Первый метод:
На AppDelegate.h:
@property(nonatomic,retain)NSString *latitude;
@property(nonatomic,retain)NSString
At AppDelegate.mlongitude;
@synthesize latitude;
@synthesize longitude;
На TabBar. м
#import "AppDelegate.h"
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
[(AppDelegate *)[[UIApplication sharedApplication] delegate] setLatitude:[NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude]];
[(AppDelegate *)[[UIApplication sharedApplication] delegate] setLongitude:[NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude]];
}
}
At my SecondView.m
#import "AppDelegate.h"
(void)viewDidLoad
{
[super viewDidLoad];
NSString *UsersCurrentLatitude = [(AppDelegate *)[[UIApplication sharedApplication] delegate] latitude];
NSString *UsersCurrentLongitude = [(AppDelegate *)[[UIApplication sharedApplication] delegate] longitude];
NSLog(@"latitude:%@,longitude%@",UsersCurrentLatitude,UsersCurrentLongitude);
}
Второй метод (я нашел учебное пособие в youtu быть и организовать этот метод для моего вопроса, поэтому он может быть бессмысленным код):
Я сделал NSObject класс, который называется SingletonClass В SingletonClass.h
#import <CoreLocation/CoreLocation.h>
@interface SingletonClass : NSObject <CLLocationManagerDelegate>
@property (nonatomic, strong) NSNumber *UsersCurrentLatitude;
@property (nonatomic, strong) NSNumber *UsersCurrentLongitude;
+(SingletonClass *) Lokasyon;
@end
В SingletonClass.m
#import "SingletonClass.h"
@implementation SingletonClass {
CLLocationManager *locationManager;
}
@synthesize UsersCurrentLongitude;
@synthesize UsersCurrentLatitude;
+(SingletonClass *)Lokasyon {
static SingletonClass *Lokasyon = nil;
if (!Lokasyon) {
Lokasyon = [[super allocWithZone:nil] init];
}
return Lokasyon;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
NSLog(@"didUpdateToLocation: %@", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
UsersCurrentLongitude = [NSNumber numberWithFloat:currentLocation.coordinate.longitude];
UsersCurrentLatitude = [NSNumber numberWithFloat:currentLocation.coordinate.latitude];
}
}
@end
в моей SeconViewController
#import "SingletonClass.h"
- (void)viewDidLoad
{
[super viewDidLoad];
NSNumber *UsersCurrentLongitude1 = [[SingletonClass Lokasyon]UsersCurrentLongitude];
NSLog(@"%@",UsersCurrentLongitude1);
}
nslog по-прежнему показывает null. я попробую Синглтон, который вы упомянули. благодарю вас в любом случае – ananana
с использованием целого класса «Singleton» просто для сохранения двух строк «**» ** не ** хорошая идея! –
ok, поэтому я должен использовать первый метод, но я все еще получаю null в NsLog. вы видите какую-либо ошибку в коде первого метода? на самом деле я могу получить локацию пользователя на каждом контроллере представления отдельно, но я думал, что это затруднит с точки зрения памяти приложения. – ananana