Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use __weak to local variable in ARC

When you write code like below in ARC

__weak NSMutableArray* array = [[NSMutableArray alloc] init];

The compiler will show you a warning or error and say "Assigning retained object to weak variable. object will be released after assignment".

But if you write like this:

__weak NSMutableArray* array = [NSMutableArray array];

There is no error.

I'm wondering if the second usage is reasonable in some situations? What's the difference between these two codes from memory management perspective? How does it work?

like image 228
Entreri Avatar asked Feb 06 '26 18:02

Entreri


1 Answers

There can be very subtle differences that the compiler cannot know.

Let's take an immutable version: [NSArray array] could return the very same static object every time. So your weak variable will point to a valid object, that has a strong reference somewhere else. Or think of the singleton pattern. On the other hand, when calling alloc/init, convention dictates that you're the only owner of that object, and that will typically leave you with nothing.

Also, the factory method certainly looks more like a (functional) method. In any case, it doesn't communicate ownership of what it returns very well. For an autoreleased object, it's not clear whether you're the the only owner or a shared owner.

like image 137
Eiko Avatar answered Feb 09 '26 09:02

Eiko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!