Iphone 使用getter访问Objective-C中结构实例变量的元素

Iphone 使用getter访问Objective-C中结构实例变量的元素,iphone,objective-c,ios,Iphone,Objective C,Ios,我有一个实例变量,它是一个结构,例如: struct Data { UInt32 i; UInt32 arr[1]; }; 在我的类中定义了一个属性: @property struct Data data; // and the corresponding @synthesize in the imp file 现在,我意识到通过数据的getter更改I和arr的值在概念上是错误的,因为我将访问getter返回的数据的副本(正确的方法是使用self->data访问它) 但是,

我有一个实例变量,它是一个结构,例如:

struct Data {
    UInt32 i;
    UInt32 arr[1];
};
在我的类中定义了一个属性:

@property struct Data data; // and the corresponding @synthesize in the imp file
现在,我意识到通过
数据的getter更改
I
arr
的值在概念上是错误的,因为我将访问getter返回的
数据的副本(正确的方法是使用
self->data
访问它)

但是,在以下方面出现了一些一般性的目标C问题:

self.data.i = 1;      // produces compile error        
self.data.arr[0] = 1; // compiles ok
首先,为什么第一行会产生编译错误,而第二行不会

第二,如果上面一行(
self.data
)中的点语法只是
[self-data]
的语法糖,为什么会出现两个不同(尽管相似)的编译错误

self.data.i = 1;   // error: Expression is not assignable
[self data].i = 1; // error: Semantic Issue: Assigning to 'readonly' return result of an objective-c message not allowed

实际上,结构是通过C(和目标C)中的值传递的。这意味着您的属性实际上返回内部“数据”类型的只读副本(右值)。赋值给临时返回的副本,编译器(正确地)将其标记为位可疑


第二行编译正确,因为
self.data.arr
返回一个只读UInt32*,但是当您用[0]对它进行索引并写入时,您不是在写入指针,而是在写入它所指向的允许的内存。

是的,这从错误消息中可以清楚看出,但是第二行的编译结果如何可以呢?@ItamarKatz遗漏了这一部分,在答案中添加了一些澄清这一点的信息。@ItamarKatz第二条语句编译并工作,因为
self.data.arr
返回指向C数组的指针,然后修改该数组的元素。换句话说,您没有修改内部结构的字段。谢谢,现在已经清楚了。从C++开始,就像是<代码> const int */COD>和 int *const >这是同样的原因,Self.Frask.Stase= CGsiZeMaKek(320460)不起作用。