ios - 设置属性导致 EXC_BAD_ACCESS 崩溃(CLLocationManager Singleton)

标签 ios objective-c swift singleton key-value-observing

过去几天我一直在想这个问题,它开始慢慢地耗尽我的精力。我正在尝试制作 CLLocationManager Singleton,因为我需要应用程序的其他两个组件的位置。但是,当我设置 currentLocation 属性时,我不断收到 EXC_BAD_ACCESS 。当我通过它时,我在 main.m 上收到一个 SIGABRT 哦,最重要的是,什么时候通过,以及 SIGABRT 我被告知我的 KVO 消息已收到但未处理,我不知道是什么这意味着。

任何帮助以及有关 KVO 的资源和/或我在使用 KVO 之前应该了解的基础知识的资源,我们将不胜感激

LocationFetch.h

@interface LocationFetch : NSObject <CLLocationManagerDelegate>

+(LocationFetch *) sharedInstance;

@property (nonatomic,strong) CLLocationManager *locationManager;
@property (nonatomic, strong) CLLocation *currentLocation;

-(void)startingUpdatingLocation;
-(void)stopUpdatingLocation;

@end

LocationFetch.m

#import "LocationFetch.h"

@implementation LocationFetch

@synthesize locationManager, currentLocation;

+(LocationFetch *) sharedInstance
{
    static LocationFetch *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc]init];
        });
    return instance;
}
- (id)init
{
    self = [super init];
    if(self)
    {

        self.locationManager = [[CLLocationManager alloc]init];
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        self.locationManager.distanceFilter = 100;
        self.locationManager.delegate = self;
        //Request Authorization
        if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])
        {
            [self.locationManager requestWhenInUseAuthorization];
        }
    }
    return self;
}
- (void)startingUpdatingLocation
{
    [self.locationManager startUpdatingLocation];
    NSLog(@"Starting Location Updates");
}
-(void)stopUpdatingLocation
{
    [self.locationManager stopUpdatingLocation];
     NSLog(@"Stopping Location Updates");
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"Location updates failed with %@", error);
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    CLLocation *location = [locations lastObject];
    NSLog(@"LocationFetch sharedInstance: Latitude %+.6f, Longitude %+.6f\n",
          location.coordinate.latitude,
          location.coordinate.longitude);
    self.currentLocation = location;
}



@end

WeatherFetch.m 的一部分(这是观察者注册的地方)

-(id)init
{
    self = [super init];
    if(self)
    {
        [[LocationFetch sharedInstance] addObserver:self forKeyPath:@"currentLocation" options:NSKeyValueObservingOptionNew context:nil];
    }
    return self;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object  

change:(NSDictionary *)change context:(void *)context
{
    if([keyPath isEqualToString:@"currentLocation"]) {
        [self setWeatherLocation];
        [self sendWeatherRequest];
        NSLog(@"Observer has received message");
        [self removeObserver:self forKeyPath:@"currentLocation" context:nil];
    }
}

编辑:这是我遵循的单例指南:http://derpturkey.com/cllocationmanager-singleton/

另一个编辑:好的,我通过删除 CLLocationManager 和 CLLocation 的强属性和非原子属性解决了 EXC_BAD_ACCESS 错误,但现在 SIGABRT 是一个更关键的问题,这是异常的调试输出。好的一面是,KVO 现在似乎已收到通知,只是不明白错误“消息已收到但未处理”

2016-06-24 21:25:51.111 TrafficAlarmClock[1504:18554] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '(
    "<CALayer: 0x7f95a043eb00>"
): An -observeValueForKeyPath:ofObject:change:context: message was received but not handled.
Key path: currentLocation
Observed object: <LocationFetch: 0x7f95a040c5a0>
Change: {
    kind = 1;
    new = "<+40.75921100,-73.98463800> +/- 5.00m (speed -1.00 mps / course -1.00) @ 6/24/16, 9:25:50 PM Eastern Daylight Time";
}
Context: 0x1050f7c08'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000105f97d85 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x0000000105682deb objc_exception_throw + 48
    2   CoreFoundation                      0x0000000105f97cbd +[NSException raise:format:] + 205
    3   Foundation                          0x00000001052e71ae -[NSObject(NSKeyValueObserving) observeValueForKeyPath:ofObject:change:context:] + 168
    4   Foundation                          0x0000000105213cad NSKeyValueNotifyObserver + 347
    5   Foundation                          0x0000000105212f39 NSKeyValueDidChange + 466
    6   Foundation                          0x00000001052e7fff -[NSObject(NSKeyValueObservingPrivate) _changeValueForKeys:count:maybeOldValuesDict:usingBlock:] + 912
    7   Foundation                          0x0000000105210804 -[NSObject(NSKeyValueObservingPrivate) _changeValueForKey:key:key:usingBlock:] + 60
    8   Foundation                          0x000000010526ea9b _NSSetObjectValueAndNotify + 261
    9   TrafficAlarmClock                   0x00000001050f2143 -[LocationFetch locationManager:didUpdateLocations:] + 227
    10  CoreLocation                        0x0000000105192418 CLClientGetCapabilities + 20974
    11  CoreLocation                        0x000000010518e823 CLClientGetCapabilities + 5625
    12  CoreLocation                        0x00000001051892dd CLClientInvalidate + 923
    13  CoreFoundation                      0x0000000105ebd2ec __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 12
    14  CoreFoundation                      0x0000000105eb2f75 __CFRunLoopDoBlocks + 341
    15  CoreFoundation                      0x0000000105eb2d28 __CFRunLoopRun + 2472
    16  CoreFoundation                      0x0000000105eb20f8 CFRunLoopRunSpecific + 488
    17  GraphicsServices                    0x0000000108660ad2 GSEventRunModal + 161
    18  UIKit                               0x000000010634ef09 UIApplicationMain + 171
    19  TrafficAlarmClock                   0x00000001050f1b6f main + 111
    20  libdyld.dylib                       0x0000000108fd192d start + 1
    21  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

另一个编辑:好的,我想我完全不明白将观察者之类的东西放置到我的应用程序中的哪里。我现在有了它,这样我的 View Controller 就是订阅者,现在我越来越接近我想要的行为。如果有人对 MVC 和 MVC/iOS 开发的软件设计有好的指南,请分享。也欢迎推荐书籍。

最佳答案

无法说出导致 KVO 错误的原因,因为缺乏精度,但只是告诉我们在类似情况下做了什么

这就是我们分配 LocationHelper 实例的方式:

- (id)init { self = [super init];

if (!self) {
    return self;
}

// Check if the service is available
if ([CLLocationManager locationServicesEnabled])
{
    // Init the location manager
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.pausesLocationUpdatesAutomatically = YES;
    self.locationManager.desiredAccuracy = LOCATION_ACCURACY_IN_METER;
}

return self;}

然后我不明白你为什么不使用:

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations

然后使用 manager.location 从此处调用 setWeatherLocation 或 sendWeatherRequest。

如果这不是您所期望的,请提供有关崩溃的更多详细信息

关于ios - 设置属性导致 EXC_BAD_ACCESS 崩溃(CLLocationManager Singleton),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38023074/

相关文章:

objective-c - #Swift 中的定义和变量

swift - tableView 中的自定义静态单元格与其他原型(prototype)单元格

swift - 在 View 中不可变的一些 View 主体变量/不透明返回

iOS 键盘在 iOS 15.4 中不显示

ios - 如何在用户关闭当前应用程序时打开另一个应用程序?

ios - 错误响应 TwitterKit

iphone - Objective-C 运行时 : Swizzled method name?

jquery - iOS 8 Webapp 状态栏在主屏幕模式下与 webapp 标题重叠

ios - 适用于 iOS 的 Swift TableView

objective-c - #import 不能防止循环调用?