2013-05-08 2 views
0

я беру местоположение пользователя с этим кодом:Как я могу использовать местоположение, которое находится в другом классе?

@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); 
} 

ответ

0

Объявить их в Appdelegate.h как-

@property(nonatomic,retain)NSString *latitude; 
    @property(nonatomic,retain)NSString *longitude; 

убедитесь, что и, синтезировать latitude и longitude свойства в AppDelegate.m классе.

Установите их в TabBar.m, где и получить место в CLLocationManager «s didUpdateToLocation:

if (currentLocation != nil) { 
    [(MyAppDelegate *)[[UIApplication sharedApplication] delegate] setLatitude:[NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude]]; 

    [(MyAppDelegate *)[[UIApplication sharedApplication] delegate] setLongitude:[NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude]]; 

     //UsersCurrentLatitude = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude]; 

     //NSLog(@"Latitude:%@,Longitude:%@",UsersCurrentLatitude,UsersCurrentLongitude); 

    } 

Доступ в другом классе (ов) как-

NSString aLatitude = [(MyAppDelegate *)[[UIApplication sharedApplication] delegate] latitude]; 
    NSString aLongitude = [(MyAppDelegate *)[[UIApplication sharedApplication] delegate] longitude]; 

PS: Есть много других способов сделать что вам нужно, например: наличие класса Singleton или сохранение в приложении iOS File system, т. е. в приложении Sandbox ..

+0

nslog по-прежнему показывает null. я попробую Синглтон, который вы упомянули. благодарю вас в любом случае – ananana

+0

с использованием целого класса «Singleton» просто для сохранения двух строк «**» ** не ** хорошая идея! –

+0

ok, поэтому я должен использовать первый метод, но я все еще получаю null в NsLog. вы видите какую-либо ошибку в коде первого метода? на самом деле я могу получить локацию пользователя на каждом контроллере представления отдельно, но я думал, что это затруднит с точки зрения памяти приложения. – ananana

Смежные вопросы