【问题标题】:Pass-by-value argument in message expression is undefined消息表达式中的按值传递参数未定义
【发布时间】:2010-06-26 16:56:06
【问题描述】:

我正在开发一个 iPhone 应用程序,但我在以下方法收到警告:

NSNumber *latitudeValue;
NSNumber *longitudeValue;

[self obtainLatitude:latitudeValue longitude:longitudeValue];

方法声明如下:

- (void) obtainLatitude:(NSNumber *)latitudeValue longitude:(NSNumber *)longitudeValue {

    NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
    [f setNumberStyle:NSNumberFormatterDecimalStyle];

    latitudeValue = [f numberFromString:[latitude.text stringByReplacingOccurrencesOfString:@"," withString:@"."]];
    longitudeValue = [f numberFromString:[longitude.text stringByReplacingOccurrencesOfString:@"," withString:@"."]];

    [f release];
}

如您所见,我正在尝试计算 latitudeValuelongitudeValue 调用 obtainLatitude:longitude: 但我做错了。

我该如何解决这个错误?

【问题讨论】:

    标签: iphone objective-c argument-passing


    【解决方案1】:

    Elfred 的回答有效,但非 NSError** 参数的传递引用非常少见。同样,坐标(通常是数值)通常存储在结构中的常规旧 C 类型中,因为相对而言,NSNumber 是相当多的开销(对于少数几个来说没什么大不了的,这将是如果您有几十个、几百个或几千个坐标,就会出现问题)。

    类似:

    struct MyLocation {
      CGFloat latitude;
      CGFloat longitude;
    };
    typedef struct MyLocation MyLocation;
    

    然后:

    - (MyLocation) mapCoordinates {
        MyLocation parsedLocation;
    
        parsedLocation.latitude = ....;
        parsedLocation.longitude = ....;
    
        return parsedLocation;
    }
    

    类似上面的内容在 iPhone/Cocoa 程序中更为典型。

    正如 Dave 所指出的,您确实不需要为此定义自己的类型。使用CLLocationCoordinate2D or CLLocation.

    【讨论】:

    • +1 或者使用CLLocationCoordinate2D,这几乎是一样的(除了它使用双精度而不是浮点数)。
    • 我使用 NSNumber 检查 latitude.text 是否为有效数字。如果您知道另一种检查方法,我会使用它。
    • 就个人而言,我只使用一个数字格式化程序来转换为 NSNumber,然后将其转换为 CLLocationCoordinate2D 中使用的标量类型。
    【解决方案2】:

    您确实是按值传递指针,因此当您重新分配它们时,它只会在您的方法中生效。一种替代方法是执行以下操作:

    - (void) obtainLatitude:(NSNumber **)latitudeValue longitude:(NSNumber **)longitudeValue {
    
        NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
        [f setNumberStyle:NSNumberFormatterDecimalStyle];
    
        *latitudeValue = [f numberFromString:[latitude.text stringByReplacingOccurrencesOfString:@"," withString:@"."]];
        *longitudeValue = [f numberFromString:[longitude.text stringByReplacingOccurrencesOfString:@"," withString:@"."]];
    
        [f release];
    

    }

    那么您的电话将如下所示:

    NSNumber *latitudeValue;
    NSNumber *longitudeValue;
    
    [self obtainLatitude:&latitudeValue longitude:&longitudeValue];
    

    【讨论】:

      猜你喜欢
      • 2011-10-24
      • 1970-01-01
      • 1970-01-01
      • 2020-01-17
      • 1970-01-01
      • 1970-01-01
      • 2017-03-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多