虽然发现了类似的问题here https://stackoverflow.com/questions/20204417/exc-bad-access-after-populating-nsmutablearray-with-custom-class-extending-clpla它没有提供答案,至少没有提供一般问题的答案。
我的问题是:
自从CoreLocation
地理编码受到速率限制,并且我正在开发应用程序的(网络)服务提供了自己的后备地理编码服务,我想使用此自定义地理编码服务,以防我达到 Apple 的速率限制。此外,我认为避免使用此自定义 REST API 返回的结果的自定义数据类型是完全有意义的,因此希望使用返回的数据来生成CLPlacemark
s。但是,文档指出CLPlacemark
属性如location, locality, administrativeArea
等是read-only
。
因此我创建了一个子类CLPlacemark
将所需的属性合成到我可以访问的私有变量上,即:
// interface: (.h)
@interface CustomPlacemark : CLPlacemark
- (nonnull id)initWithLocation: (nonnull CLLocation *)location
locality: (nullable NSString *)locality
administrativeArea: (nullable NSString *)adminArea
country: (nullable NSString *)country;
@end
// implementation (.m)
@implementation CustomPlacemark
@synthesize location = _location;
@synthesize locality = _locality;
@synthesize country = _country;
@synthesize administrativeArea = _administrativeArea;
- (nonnull id)initWithLocation: (nonnull CLLocation *)location
locality: (nullable NSString *)locality
administrativeArea: (nullable NSString *)adminArea
country: (nullable NSString *)country{
self = [super init];
if(self){
_location = location;
_locality = locality;
_administrativeArea = adminArea;
_country = country;
}
return self;
}
@end
使用单元测试测试此代码,该测试解析 JSON 文件中的数据并调用我的initWithLocation: locality: administrativeArea: country:
方法与数据结果EXC BAD ACCESS (code=1)
在测试结束时(在结束时}
测试方法的),地标变量指向nil
虽然之前有过NSLog(@"placemark: %@", customPlacemark);
输出正确的值。此外,逐行执行测试显示CustomPlacemark
工作(即指向正确填充的对象)直到到达测试结束。对我来说,这表明我的CustomPlacemark
出了问题——但到底是哪里出了问题?
任何帮助是极大的赞赏!
作为对遇到类似问题的任何人的参考:
经过一番密集的 Google-Fu 和深入研究苹果的资料来源后,似乎扩展了CLPlacemark
不是有意的。
但是,我能够根据发现的提示实施解决方法here http://szulctomasz.com/unit-testing-in-swift-with-clplacemark/,这基本上滥用了这样一个事实:MKPlacemark
延伸CLPlacemark
并提供了一种用自定义数据初始化的方法,即- (instancetype _Nonnull)initWithCoordinate:(CLLocationCoordinate2D)coordinate addressDictionary:(NSDictionary<NSString *, id> * _Nullable)addressDictionary
。寻找正确的钥匙addressDictionary
将所需的属性映射到CLPlacemark
可能需要一些尝试和错误,特别是因为ABPerson/Address
iOS 9 中已弃用该功能。
我找到的用于我目的的密钥是:
@"City" -> CLPlacemark.city
@"State" -> CLPlacemark.administrativeArea
@"Country" -> CLPlacemark.country
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)