与核心位置pipe理器对象一起使用时,initWithCoder实际上在做什么?

好的,我想用initWithCoder完全理解这段代码。 在阅读了几篇build议的文档并阅读了一本关于授权,核心位置,指定初始化程序的书的章节之后,我想这就是我想要做的。

  • 使用指向NSCoder对象的指针初始化我的viewcontroler。
  • 如果这个工作,然后创build一个位置pipe理器对象的实例
  • 使委托我的viewcontroller。
  • 将位置精度设置为最佳。
  • 告诉位置pipe理员开始更新。

  • 将存储在委托中的信息logging到控制台。 lat和long存储在一个作为parameter passing给locationManager:DidUpdateLocations:方法的NSArray对象的指针中。

  • 如果没有find位置,请在控制台中logging此状态。

.h接口文件:

#import <UIKit/UIKit.h> #import <CoreLocation/CoreLocation.h> @interface WhereamiViewController : UIViewController { CLLocationManager *locationManager; } @end 

.m执行文件:

 #import "WhereamiViewController.h" @interface WhereamiViewController () @end @implementation WhereamiViewController - (id)initWithCoder:(NSCoder *)aDecoder { self = [super initWithCoder:aDecoder]; if (self){ //create location manager object locationManager = [[CLLocationManager alloc] init]; //there will be a warning from this line of code [locationManager setDelegate:self]; //and we want it to be as accurate as possible //regardless of how much time/power it takes [locationManager setDesiredAccuracy:kCLLocationAccuracyBest]; //tell our manager to start looking for its location immediately [locationManager startUpdatingLocation]; } return self; } - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations { NSLog(@"%@", locations); } - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { NSLog(@"Could not find location: %@", error); } @end 

还有一些问题:

1)代码的setDelegate部分是否重要,因为那是“startUpdatingLocation方法将存储它的数据?

2)数据是否存储存档? 我问,因为我设置的委托具有初始化initWithCoder的事实。 从我读到的是存档数据的parsing器。 所以也许从locationManager的信息是存档的,如果有意义的话,需要解压缩。

我在XCode上得到这个警告。 难道我做错了什么? 在这里输入图像说明 我是否还想这样设置代表,还是有新的方法呢? 在另一篇文章中,我记得看到一个类似于<UIViewControllerDelegate>的答案,并被告知把它放在我的接口文件中。

我意识到,这篇文章的大部分可能没有意义,我可能是完全错误的,但我从我的失败中学到最多,也许其他人将来,如果他们select学习开发ios。

谢谢你的时间。

问候

总的来说,是的。

1)是的,这很重要。 它告诉位置经理谁想知道位置更新。 startUpdatingLocation不在startUpdatingLocation中存储数据。 startUpdatingLocation触发定位系统启动并找出你在哪里。 代表被告知有关的位置,可以做它想要的。

2) initWithCoder从档案中重新创buildWhereamiViewController 。 该档案最有可能是一个XIB或故事板。 它与位置经理或代表关系无关。

正如@ArkadiuszHolko所说,你应该指定<CLLocationManagerDelegate> 。 这样做的目的是告诉编译器,你承诺实现协议所需的方法,所以它可以检查你是否提出了一个问题,否则。

1)代码的setDelegate部分是否重要,因为那是“startUpdatingLocation方法将存储它的数据?

是的,您将无法从CLLocationManager接收数据,因为它不知道在哪个对象上调用locationManager:didUpdateLocations:locationManager:didFailWithError:以及其他尚未实现的方法。 您应该熟悉Objective-C中的委托模式 。

2)数据是否存储存档? 我问,因为我设置的委托具有初始化initWithCoder的事实。 从我读到的是存档数据的parsing器。 所以也许从locationManager的信息是存档的,如果有意义的话,需要解压缩。

数据将不会被存档,因为您不会将其存储在任何地方。 CLLocationManager也不CLLocationManager数据存储在任何地方。

我在XCode上得到这个警告。 难道我做错了什么?

您错过了您的视图控制器符合CLLocationManagerDelegate协议的声明。 你可以通过replace来解决它:

 @interface WhereamiViewController () 

有:

 @interface WhereamiViewController () <CLLocationManagerDelegate> 

你应该阅读关于在Objective-C中使用协议的内容 。