Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing elements of a struct instance variable in Objective-C using the getter

I have an instance variable which is a struct, for example:

struct Data {
    UInt32 i;
    UInt32 arr[1];
};

And a property is defined in my class:

@property struct Data data; // and the corresponding @synthesize in the imp file

Now, I am aware that changing the values of i and arr through the getter of data is conceptually wrong, since I will be accessing the copy of data returned by the getter (the correct way is accessing it using self->data).

However some general Objective-C questions arise regarding the following lines:

self.data.i = 1;      // produces compile error        
self.data.arr[0] = 1; // compiles ok

First, why does the first line produces a compile error, and the 2nd line does not?

Second, if the dot syntax in the above line (self.data) is just a syntactic sugar to [self data], why do I get 2 different (although similar) compile errors?

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
like image 817
Itamar Katz Avatar asked Mar 23 '26 10:03

Itamar Katz


1 Answers

Actually, structs are passed by value in C (and Objective C). That means that your property actually returns a read only copy (rvalue) of the internal "Data" type. The assignment is to the temporary returned copy, which the compiler (rightfully) flags as a bit suspect.

The second line that compiles correctly does so since self.data.arr returns a read only UInt32*, but when you index it with [0] and write to that, you're not writing to the pointer, you're writing to the memory that it points to which is allowed.

like image 194
Joachim Isaksson Avatar answered Mar 25 '26 00:03

Joachim Isaksson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!