user1802143
user1802143

Reputation: 15682

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.

Upvotes: 4

Views: 328

Answers (3)

Carl Veazey
Carl Veazey

Reputation: 18363

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.

Upvotes: 2

an0
an0

Reputation: 17530

There is no destructor semantics for C struct. ARC has no clue when to release the object fields in such a struct. Symmetrically, there is neither copy constructor — struct assignment is simply bitwise copy, thus ARC can neither do retain for object fields.

Upvotes: 1

Rob
Rob

Reputation: 437632

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.

Upvotes: 4

Related Questions