2012-02-07 43 views
0

讓我來說說我是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的某個方法在內部調用的方法。我確信我在某個地方犯了一個業餘的錯誤,有人能指出我的方向嗎?

回答

2

你的問題是你的屬性中使用了「複製」CLLocationManager,這是一個單例 - 通常Singletons被定義爲它們會拋出異常以防止複製單個實例。

相反,聲明你的財產,像這樣:

@property(nonatomic, strong) CLLocationManager *locManager; 
相關問題