2014-11-12 7 views
-1

Я пытаюсь следовать этот учебник: http://www.appcoda.com/how-to-get-current-location-iphone-user/Использование необъявленной идентификатора «locationManager»

Все это хорошо, пока я не добавить эту строку: locationManager = [[CLLocationManager Alloc] инициализации]; Затем я получаю сообщение об ошибке.

Я также получаю ошибки для этих линий: (Xcode предлагает я использую «_LongitudeLabel»

if (currentLocation != nil) { 
    longitudeLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude]; 
    latitudeLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude]; 
} 

Любая идея, что это неправильно есть ли учебник ошибки или я сделал что-то неправильно Спасибо

?!

Это ViewController.m файл:

#import "ViewController.h" 

@implementation MyLocationViewController { 
CLLocationManager *locationManager; 
} 
@end 

@interface ViewController() 
@end 

@implementation ViewController 

- (void)viewDidLoad { 
[super viewDidLoad]; 
// Do any additional setup after loading the view, typically from a nib. 
locationManager = [[CLLocationManager alloc] init]; 
} 

- (void)didReceiveMemoryWarning { 
[super didReceiveMemoryWarning]; 
// Dispose of any resources that can be recreated. 
} 

- (IBAction)getCurrentLocation:(id)sender { 
locationManager.delegate = self; 
locationManager.desiredAccuracy = kCLLocationAccuracyBest; 

[locationManager startUpdatingLocation]; 
} 

#pragma mark - CLLocationManagerDelegate 

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error 
{ 
NSLog(@"didFailWithError: %@", error); 
UIAlertView *errorAlert = [[UIAlertView alloc] 
          initWithTitle:@"Error" message:@"Failed to Get Your Location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
[errorAlert show]; 
} 

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 
{ 
NSLog(@"didUpdateToLocation: %@", newLocation); 
CLLocation *currentLocation = newLocation; 

if (currentLocation != nil) { 
    longitudeLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude]; 
    latitudeLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude]; 
} 
} 

@end 

Это ViewController.h файл:

// ViewController.h 
// MyLocationDemo 
// 
// Created by Ian Nicoll on 12/11/14. 
// Copyright (c) 2014 Ian Nicoll. All rights reserved. 
// 
#import <CoreLocation/CoreLocation.h> 
#import <UIKit/UIKit.h> 

@interface ViewController : UIViewController 
@property (weak, nonatomic) IBOutlet UILabel *LatitudeLabel; 
@property (weak, nonatomic) IBOutlet UILabel *LongitudeLabel; 
@property (weak, nonatomic) IBOutlet UILabel *addressLabel; 
- (IBAction)getCurrentLocation:(id)sender; 
@end 

@interface MyLocationViewController : UIViewController <CLLocationManagerDelegate> 
@end 

ответ

0

Первая проблема - это ошибка с вашей стороны. Вы объявили locationManager в MyLocationViewController, но попробуйте инициализировать его в viewDidLoad от ViewController, где его, конечно, не существует.

Вторая проблема связана с инструкциями. Когда вы объявляете @property, поведение по умолчанию заключается в создании переменной экземпляра с подчеркиванием перед ним.

К @property (weak, nonatomic) IBOutlet UILabel *LatitudeLabel; может быть использован как self.latitudeLabel (который проходит через сеттер/геттер) или только _latitudeLabel, который напрямую обращается к ivar. Последнее, вероятно, то, что вы хотите.

+0

спасибо, я все еще застряло с первым вопросом, что же мне делать, чтобы исправить это, я пытаюсь переместить декларацию везде LOL, но не уверен, где я предположу, что, чтобы переместить его в положении, ничего работает! – Nicoll

+0

Либо переместите объявление переменной в 'ViewController', либо переместите весь код, который использует эту переменную, в' MyLocationViewController' – Dima

0

Хорошо, теперь сборка выполнена успешно (хотя я не 100 & уверен, что все правильно), но теперь я получаю предупреждение для этой строки: locationManager.delegate = self; - Назначение «id'from несовместимого типа» ViewControler * const_strong ' Вы знаете, как исправить это предупреждение?

#import "ViewController.h" 

@interface ViewController() 
@end 

@implementation ViewController { 
CLLocationManager *locationManager; 
} 

- (void)viewDidLoad { 
[super viewDidLoad]; 
// Do any additional setup after loading the view, typically from a nib. 
locationManager = [[CLLocationManager alloc] init]; 
} 

- (void)didReceiveMemoryWarning { 
[super didReceiveMemoryWarning]; 
// Dispose of any resources that can be recreated. 
} 

- (IBAction)getCurrentLocation:(id)sender { 
locationManager.delegate = self; 
locationManager.desiredAccuracy = kCLLocationAccuracyBest; 

[locationManager startUpdatingLocation]; 
} 

#pragma mark - CLLocationManagerDelegate 

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error 
{ 
NSLog(@"didFailWithError: %@", error); 
UIAlertView *errorAlert = [[UIAlertView alloc] 
          initWithTitle:@"Error" message:@"Failed to Get Your Location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
[errorAlert show]; 
} 

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 
{ 
NSLog(@"didUpdateToLocation: %@", newLocation); 
CLLocation *currentLocation = newLocation; 

if (currentLocation != nil) { 
    _LongitudeLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude]; 
    _LatitudeLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude]; 
} 
} 

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