IOS: why don't you have objects in structures?

I was wondering why you cannot create objects in structures when using ARC. Whenever I do this, I get an error

ARC forbids objective-c objects in structures

I have seen many answers that discuss solutions, but no one discusses the reason why it does not work in the first place.

+4
source share
3 answers

If you look at the Go to ARC Release Notes , it says:

You cannot use object pointers in C. structures

Instead of using a structure, you can create an Objective-C class to manipulate data instead.

If you are watching a video of WWDC 2011 Introducing automatic reference counting , it raises the question of why this is so on a slide called β€œRule No. 2” / 4: There are no object pointers in C-structures (slide # 21), namely:

The compiler needs to know when links come and go

  • Pointers must be zero initialized

  • Release when the link disappears

Structures

Cs do not satisfy this criticism, so they advise using objects instead. You can use __unsafe_unretained in conjunction with C structures, but that means the name becomes obvious, insecure, and harms many of the benefits of ARC.

+4
source

In the general case, the lifetime of a struct not easy to derive at compile time, and the consequence of this is that if references to ownership were allowed in the structure, they mentioned the ability to reason about the lifetime of objects, which would be very complicated during compilation.

clang docs explicitly refer to this complication.

+2
source

There is no destructor semantics for C struct. ARC has no idea when to release object fields in such a structure. There is no constructor-constructor symmetrically - the purpose of the structure is just bitwise copying, so ARC cannot save the fields of the object.

+1
source

Source: https://habr.com/ru/post/1499011/


All Articles