使用对象时出错:“左值作为赋值的左操作数需要左值”

时间:2009-07-20 12:30:39

标签: iphone objective-c

在为我的一个对象赋值时,我收到一个奇怪的错误。尽我所知,编译器认为我正在分配一个只读变量。它在myPlace.publicLocation ...行上给了我“左值作为赋值的左值”。

我确定这是一个经典的新手错误 - 我哪里错了?

CSPlace *myPlace;
myPlace.publicLocation.coordinate.latitude = 
    [[separatedData objectAtIndex:0] floatValue];

类:

#import <CoreLocation/CLLocation.h>
@interface CSPlace : NSObject {
    CLLocation *publicLocation;
}
@property (copy, nonatomic) CLLocation *publicLocation;
@end
#import "CSPlace.h"
@implementation CSPlace
@synthesize publicLocation;
@end

4 个答案:

答案 0 :(得分:6)

CLLocation一个关于纬度和经度的不可变类。所以你不能修改它的纬度。您必须创建一个新对象:

[[CLLocation alloc] initWithLatitude:latitude longitude:longitude];

不可变是拥有这样一个初始化器的全部意义。

答案 1 :(得分:0)

我不是Objective-C专家,但我知道它是C-superset ......所以不应该是:

myPlace->publicLocation->coordinate.latitude

(用“ - &gt;”而不是“。”,我不知道“坐标”,如果它是指针或不是)

编辑:此外,如果您尝试访问未分配对象的属性,您的程序很可能会崩溃,但未分配 myPlace

编辑2:请参阅以下johne的评论,了解为什么我的答案应该被忽略。 (我正在离开它,因为有一天可能会有人犯同样的错误)

答案 2 :(得分:0)

coordinate definedCLLocation的只读属性...所以看来您需要创建一个新的CLLocation而不是更改坐标值现有的。

答案 3 :(得分:0)

  

尽我所知,编译器认为我正在分配一个只读变量。

您正在尝试分配给只读属性:

@property(readonly, nonatomic) CLLocationCoordinate2D coordinate;