__unsafe_unretained NSString struct var

前端 未结 4 1074
鱼传尺愫
鱼传尺愫 2021-01-03 10:38

I am trying to create a structure that has several different variable of different types in it.

several of the types are of NSString, but trying to do this was caus

4条回答
  •  执念已碎
    2021-01-03 11:02

    ARC just loves to complain! Actually, we have to look at this historically. In the old-style Manual Reference Counted environment from way back, the compiler didn't complain because it knew everything memory related was going to be your job, and your job alone. But that changed when Apple introduced Automatic Reference Counting, because the compiler needed to get substantially more anal about what type an object was and what it was contained in, so that it knew how to properly manage the memory for said object efficiently. When you place an Objective-C object into a C-struct, you're sort of sticking out your tongue at the compiler because a struct implies that you will own and manage the memory of the items inside of it yourself (that and ARC doesn't touch malloc and free). That's where __unsafe_unretained comes in. With it, we tell the compiler that any and all memory operations will be your responsibility, just like in MRC. ARC literally "can't guarantee the safety" of the object's pointer being nil after deallocation, so it makes you explicitly declare it as such.

    If you want to avoid all of this nonsense, just make your struct into a lightweight class and declare your objects normally. After all, classes in Objective-C are just C-structs-(ish) with a lot of Apple magic thrown in.

提交回复
热议问题