I was wondering why you cannot have objects in structs when using ARC. Whenever I do, I get the error
ARC forbids objective-c objects in structs
I saw many answers that discuss solutions, but none discuss the underlying reason why it doesn't work in the first place.
If you look at the Transitioning to ARC Release Notes, it says:
You cannot use object pointers in C structures.
Rather than using a struct, you can create an Objective-C class to manage the data instead.
If you watch WWDC 2011 video Introducing Automatic Reference Counting, it touches on the point why this is the case on the slide titled Rule #2/4: No Object Pointers in C Structs (slide #21), namely that:
Compiler must know when references come and go
Pointers must be zero initialized
Release when reference goes away
C structs don't satisfy that critiera, which is why they advise using objects instead. You could use __unsafe_unretained
in conjunction with C structs, but that is, as the name makes obvious, unsafe, and defeats many of the benefits of ARC.
In general, the lifetime of a struct
is not easy to infer at compile time, and a consequence of this is that if ownership-qualified references were allowed in a struct, the ability to reason about the lifetime of the objects they referred to would be severely complicated at compile time.
The clang docs refer to this complication explicitly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With