无法识别的选择器发送到合成属性的实例

时间:2012-02-07 06:46:03

标签: objective-c ios exception memory selector

让我有资格说我是Objective-C / iOS的新手。

我的程序在未捕获的异常NSInvalidArgumentException, reason: [CLLocationManager copyWithZone:]: unrecognized selector sent to instance.上崩溃这似乎是一个非常常见的错误,而且我可以说,它通常发生在内存管理出错的情况下。我在stackoverflow和Google上看过类似的问题,但似乎没有一个相同。

我的应用程序是一个简单的单一视图应用程序。我正在尝试使用CLLocationManager类,因为我想获得用户的标题。我的代码:

magnetoTestViewController.h

#import <UIKit/UIKit.h>
@class CLLocationManager;

@interface magnetoTestViewController : UIViewController
@property(copy, readwrite) CLLocationManager *locManager;
@end

magnetoTestViewController.m

#import "magnetoTestViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface magnetoTestViewController()
- (void)startHeadingEvents;
@end

@implementation magnetoTestViewController

@synthesize locManager = _locManager;

...

- (void)startHeadingEvents {
NSLog(@"entered startHeadingEvents()");
if (!self.locManager) {
    CLLocationManager* theManager = [[CLLocationManager alloc] init];

    // Retain the object in a property.
    self.locManager = theManager;
    self.locManager.delegate = self;
}

// Start location services to get the true heading.
self.locManager.distanceFilter = 1000;
self.locManager.desiredAccuracy = kCLLocationAccuracyKilometer;
[self.locManager startUpdatingLocation];

// Start heading updates.
if ([CLLocationManager headingAvailable]) {
    NSLog(@"Yep, the heading is available.");
    self.locManager.headingFilter = 5;
    [self.locManager startUpdatingHeading];
}
else {
    NSLog(@"*sadface*, the heading information is not available.");
}
NSLog(@"exited startHeadingEvents()");
}

- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading {
NSLog(@"locationManagerdidUpdateHeading() was called.");
if (newHeading.headingAccuracy < 0) {
    NSLog(@"the heading accuracy is smaller than 0.  returning.");
    return;
}

// Use the true heading if it is valid.
CLLocationDirection theHeading = ((newHeading.trueHeading > 0) ?
                                  newHeading.trueHeading : newHeading.magneticHeading);
NSString* myNewString = [NSString stringWithFormat:@"the heading is %d", theHeading];
NSLog(myNewString);

}

我的代码正在输入startHeadingEvents方法(基于我的日志记录)但在退出方法之前崩溃(基于我的日志记录未被调用)。我假设copyWithZone(在错误中)是在某个时刻内部调用CLLocationManager的方法。我确定我在某个地方犯了一个业余错误,有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:2)

您的问题是您在属性中使用“复制”作为CLLocationManager,这是一个单例 - 通常会定义单例,以便它们抛出异常以防止复制单个实例。

相反,请声明您的财产:

@property(nonatomic, strong) CLLocationManager *locManager;