2012-05-10 41 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中的内存管理。 –