Alexandre G
Alexandre G

Reputation: 1693

Is __weak required? What's it for in this case? Will it leak?

I have come across this code and used it to tint an image on a button successfully until it started failing in iOS 9 release builds:

UIImage * __weak image = [[self imageForState:UIControlStateNormal]
                                   imageWithRenderingMode:renderingMode];
[self setImage:image forState:UIControlStateNormal];

I've shrugged at the __weak when I first saw it used in this case, but then have also seen it used elsewhere in similar cases, so considered it right without really understanding what it's for.

Removing it fixes the iOS 9 release build bug where the image does not appear on the button at all (as I imagine due to more aggressive memory optimisations that deallocate the image right away), but I was wondering:

Was there a need for the __week in the first place, and if so, why, and will removing it result in a leaked UIImage?

Edit: Heres a simple class that does the same thing and exhibits the same behaviour, in case someone needs an "in context" example: https://github.com/tdginternet/TGCameraViewController/blob/master/TGCameraViewController/Classes/UI/TGTintedButton.m

Upvotes: 1

Views: 125

Answers (1)

howanghk
howanghk

Reputation: 3090

Do not set __weak on local variables if the object it reference may not be strongly referenced by another party.

In the code you posted, as the object (image) is created on-the-fly and ownership is passed to the caller, the caller is responsible to hold a strong reference to it, at least during the lifespan of the caller. If the system see no strong reference to the object and may deallocate it at any time. In a release build, the object is deallocated and the weak reference is updated to nil before the setImage call. Here we should use a typical strong reference to the image, and as the local variables will be gone after the method call, the strong reference will be released.

To answer your question:

  1. __weak is not required, and is actually wrong here
  2. The author wants to avoid holding strong reference to image
  3. No it won't leak

Wikipedia have a good article about Automatic Reference Counting which explains how ARC and weak references work.

Hope this helps!

Upvotes: 1

Related Questions