Objective-C - 将变量传递给函数时的错误

时间:2013-05-24 11:01:35

标签: iphone ios objective-c cordova

将var传递给另一个函数的最简单方法是什么?

- (void)locationManager:(CLLocationManager *)manager 
    didUpdateToLocation:(CLLocation *)newLocation 
           fromLocation:(CLLocation *)oldLocation {

   NSLog(@"%@", started);
}

我试过了:

定义了一个全球变量:

extern NSString *started;

当我直接设置NSString并传入另一个函数时,它运行良好:

-(void) startTracking:(CDVInvokedUrlCommand*)command {
  started = @"testing";
}

但它不起作用:

-(void) startTracking:(CDVInvokedUrlCommand*)command {

  NSString* myarg = [command.arguments objectAtIndex:0]; // http://docs.phonegap.com/en/2.5.0/guide_plugin-development_ios_index.md.html#Developing%20a%20Plugin%20on%20iOS_writing_an_ios_cordova_plugin
  started = myarg;
}

(我是一个客观的C初学者,不太了解它)

编辑:当我将应用程序置于后台时,似乎只会崩溃。

2 个答案:

答案 0 :(得分:0)

根据您是否使用ARC,您必须保留该对象。你可能想在你的班级上使用一个属性:

标题中的

@property(strong) NSString *started;

实施中:

-(void)locationManager:(CLLocationManager *)manager 
didUpdateToLocation:(CLLocation *)newLocation 
       fromLocation:(CLLocation *)oldLocation {

 NSLog(@"%@", self.started);
}

-(void) startTracking:(CDVInvokedUrlCommand*)command {
  self.started = @"testing";
}

-(void) startTracking:(CDVInvokedUrlCommand*)command {

 NSString* myarg = [command.arguments objectAtIndex:0];
 self.started = myarg;
}

答案 1 :(得分:0)

Mate,好像你想跟踪你开始接收位置信息的日期。

这样做怎么样:

// Your .h file
@interface MyClass <CLLocationManagerDelegate>
{
    BOOL hasStartedUpdatingLocation;
    NSDate *startDate;

    CLLocationManager *locationManager;
}

...

// Your .m file
- (void)locationManager:(CLLocationManager *)manager 
    didUpdateToLocation:(CLLocation *)newLocation 
           fromLocation:(CLLocation *)oldLocation 
{
    // ---------------------------------------------------------------
    // if has NOT started updating location, record start date
    // otherwise, do not execute this if statement
    // ---------------------------------------------------------------
    if(!hasStartedUpdatingLocation)
    {
        hasStartedUpdatingLocation = YES;

        // this if statement should only execute once
        startDate = [NSDate date]; // get the current date and time
    }
    else
    {
        // do something else
    }
}