Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: why can't you have objects in structs?

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.

like image 570
user1802143 Avatar asked Mar 22 '23 15:03

user1802143


2 Answers

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.

like image 125
Rob Avatar answered Mar 29 '23 17:03

Rob


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.

like image 44
Carl Veazey Avatar answered Mar 29 '23 18:03

Carl Veazey