好的,所以我想用 initWithCoder 完全理解这段代码中发生了什么。 在阅读了几个建议的文档并一遍又一遍地阅读一本关于委托(delegate)、核心位置、指定初始化程序的书中的章节后,我认为这是发生了什么。
- 使用指向 NSCoder 对象的指针初始化我的 View Controller 。
- 如果可行,则创建位置管理器对象的实例
- 让委托(delegate)成为我的 View Controller 。
- 将位置精度设置为最佳。
告诉位置管理员开始更新。
将“存储在委托(delegate)中”的信息记录到控制台。纬度和经度存储在指向 NSArray 对象的指针中,该对象作为参数传入 locationManager:DidUpdateLocations: 方法。
如果找不到位置,也会在控制台中记录此状态。
.h接口(interface)文件:
#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) 存储的数据是否归档?我问是因为我设置的委托(delegate)具有初始化程序 initWithCoder。从我读到的内容来看,这是一个归档数据的 unarchiver。因此,也许来自 locationManager 的信息已存档,如果有意义,则需要取消存档。
我在 XCode 上收到此警告。难道我做错了什么?
我是否仍然应该以这种方式设置代表,或者是否有一种新的方式来设置代表?在另一篇文章中,我记得看到类似 <UIViewControllerDelegate>
的答案并被告知将其放入我的界面文件中。
我意识到这篇文章的大部分内容可能没有意义,我可能完全错了,但我从我的失败中学到了很多东西,如果其他人选择学习为 ios 开发,也许他们将来也会这样做。
感谢您的宝贵时间。
问候
最佳答案
总的来说,是的。
1) 是的,这很重要。它告诉想要了解位置更新的位置管理员。 startUpdatingLocation
不在委托(delegate)中存储数据。 startUpdatingLocation
触发定位系统启动并找出您的位置。代表会被告知位置并可以用它做它想做的事。
2) initWithCoder
重新创建 WhereamiViewController
来自文件。该文件很可能是 XIB 或 Storyboard。它与位置管理器或委托(delegate)关系无关。
正如@ArkadiuszHolko 所说,您应该指定 <CLLocationManagerDelegate>
.这样做的目的是告诉编译器您 promise 实现协议(protocol)所需的方法,以便它可以检查您是否提出了问题。
关于ios - 当与核心位置管理器对象结合使用时,initWithCoder 实际上在做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19367654/