2012-05-10 40 views
1

我正在爲unity3D創建一個iOS插件。下面是代碼。在使用EXC_BAD_EXCESS調用[regionMonitor startMonitor]函數時,如何爆炸。根據互聯網的帖子,這似乎是一個內存管理錯誤。任何人都可以看到這裏有什麼問題。謝謝。爲CLLocationManager創建插件

「RegionMonitoringPlugin.h」

#import <Foundation/Foundation.h> 
#import <CoreLocation/CoreLocation.h> 


@interface RegionMonitoringPlugin : NSObject <CLLocationManagerDelegate> 
{ 
    CLLocationManager *locationManager; 
} 

-(void)leavingHomeNotify; 
-(void)startMonitor:(float)latitude longitude:(float)longitude radius:(float)raduis; 

@end 

「RegionMonitoringPlugin.mm」

#import "RegionMonitoringPlugin.h" 

@implementation RegionMonitoringPlugin 

- (id) init 
{ 
    if (self = [super init]) 
    { 
     locationManager = [[[CLLocationManager alloc] init] autorelease]; 
     locationManager.delegate = self; 
     [locationManager setDistanceFilter:kCLDistanceFilterNone]; 
     [locationManager setDesiredAccuracy:kCLLocationAccuracyBest]; 
    } 
return self; 
} 

-(void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region 
{ 
    [self leavingHomeNotify]; 
} 

-(void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region 
{ 
    [self leavingHomeNotify]; 
} 

- (void)locationManager:(CLLocationManager *)manager monitoringDidFailForRegion:(CLRegion *)regionwithError:(NSError *)error 
{ 
    NSLog(@"Location error %@, %@", error, @"Fill in the reason here"); 
} 

-(void)leavingHomeNotify 
{ 
UILocalNotification *note = [[UILocalNotification alloc] init]; 
note.alertBody= @"Region Left"; 
[[UIApplication sharedApplication] presentLocalNotificationNow:note]; 
[note release]; 
} 

-(void)startMonitor:(float)latitude longitude:(float)longitude radius:(float)radius 
{ 
    CLLocationCoordinate2D home; 
    home.latitude = latitude; 
    home.longitude = longitude; 
    CLRegion* region = [[CLRegion alloc] initCircularRegionWithCenter:home radius:radius identifier:@"home"]; 
    [locationManager startMonitoringForRegion:region desiredAccuracy:kCLLocationAccuracyBest]; 
    [region release];  
} 

@end 

extern "C" { 

    static RegionMonitoringPlugin *regionMonitor; 

    // Unity callable function to start region monitoring 
    BOOL _startRegionMonitoring(float m_latitude,float m_longitude, float m_radius) 
    { 
     if (![CLLocationManager regionMonitoringAvailable] || ![CLLocationManager regionMonitoringEnabled]) 
      return NO; 
     if (regionMonitor == nil){ 
      regionMonitor = [[[RegionMonitoringPlugin alloc]init ] autorelease]; 
     } 
     [regionMonitor startMonitor:m_latitude longitude:m_longitude radius:m_radius]; 
     return YES; 

    } 
} 
+0

Unity標籤用於Microsoft Unity。請不要濫用它。 –

回答

1

如果我沒有看到它,你不應該autoreleaselocationManager也不regionMonitor

添加一個dealloc方法代替releaselocationManager。一旦停止位置監控,應該釋放regionMonitor

+0

謝謝。這工作! ...你能告訴我爲什麼autorelease不起作用嗎? – ila

+0

由於'autoreleasing'對象會導致它在一些方法返回給調用者後被釋放(並因此在這種情況下被銷燬)。所以你試圖訪問一個不存在的對象。如果你不明白,你應該閱讀iOS中的內存管理。 –