Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
分配到只读属性错误iOS 6_Ios_Objective C_Properties_Ios6_Attributes - Fatal编程技术网

分配到只读属性错误iOS 6

分配到只读属性错误iOS 6,ios,objective-c,properties,ios6,attributes,Ios,Objective C,Properties,Ios6,Attributes,我有一个名为Constants的单例类,我需要在其中设置一些应用程序范围的常量。我希望这些常量是只读的。因此,我在Constants.h文件中执行了以下操作 @interface Constants : NSObject { } @property (nonatomic, readonly)double U_LAT; @property (nonatomic, readonly)double U_LNG; 然后在我的.m文件中,我得到了这个方法 -(id)init {

我有一个名为Constants的单例类,我需要在其中设置一些应用程序范围的常量。我希望这些常量是只读的。因此,我在Constants.h文件中执行了以下操作

 @interface Constants : NSObject
 {

 }

 @property (nonatomic, readonly)double U_LAT;
 @property (nonatomic, readonly)double U_LNG;
然后在我的.m文件中,我得到了这个方法

 -(id)init
 {
     self = [super init];

     self.U_LAT = 49.2765;
     self.U_LNG = -123.2177;

     return self;
 }
我从以下代码中获得此错误:

 Assignment to readonly property

我不能在init方法中初始化只读变量吗?如果没有,如何初始化它们?

self.propertyName=val
[self-setPropertyName:val]相同--它需要一个setter方法才能存在。只读属性没有setter方法

您可以设置直接支持属性的ivar,但是:

-(id)init
 {
     self = [super init];

     _U_LAT = 49.2765;
     _U_LNG = -123.2177;

     return self;
 }
如果允许自动合成属性,则ivar的名称将是以下划线为前缀的属性名称。如果您有一个显式的
@name,ivar将具有相同的名称。您还可以使用synthesis语句创建任意名称的变量:
@synthesis cat=dog


属性也可以公开为只读,但可由类写入;这涉及到在类扩展中声明setter方法或。

我认为更好的方法是在私有接口中重新声明属性,如下所示:

// .h

@interface Constants : NSObject
@property(nonatomic, readonly) double U_LAT;
@end

// .m

@interface Constants ()
@property(nonatomic, readwrite) double U_LAT;
@end

是的,在inits和dealoc中,直接将变量称为___LAT。

最好不要将它们声明为属性,而是作为常量

.h
文件中,在
@界面上方添加以下代码:

extern double const U_LAT;
extern double const U_LNG;
double const U_LAT = 49.2765;
double const U_LNG = -123.2177;
然后在
.m
文件中,在
@界面上方添加以下代码:

extern double const U_LAT;
extern double const U_LNG;
double const U_LAT = 49.2765;
double const U_LNG = -123.2177;
U_LAT
U LNG
将可用于导入
常量.h
的任何类,并且您不必处理属性或接口


正是为了这类事情,
const
才被发明出来。

或者更好地将它们称为
self.U\U LAT
。扎夫:强烈建议在初始化期间使用访问器方法(
self.foo
)。最好使用下划线变量
\u foo