Is this delegate property strongly referenced or not?

69 views Asked by At

I have a problem in one of my VCs called ArticleViewController. The dealloc method is never called, and when the view is opened and closed three times, there are three VCs alive.

I read here (great source when you have a retain cycle in your ViewController!) the following:

If you use

someObj.delegate = self;

inside the view controller, check the delegate property on someObj is weak.

@property (nonatomic, weak) id delegate;

One of the snippets in my VC is:

PopViewController *pop=[[PopViewController alloc] initWithNibName:@"PopViewController" bundle:nil];
pop.delegate = self;

So I check in PopViewController.h if the property is weak.

@property (nonatomic, assign) id <PopViewControllerDelegate> delegate;

Since strong is the default, and there is no explicit weak here, would this cause my retain cycle? I am bit in doubt, because I see the same thing in the header file of e.g. UIPopoverController.h, which is in the UIKit.

@property (nonatomic, assign) id <UIPopoverControllerDelegate> delegate;
2

There are 2 answers

4
Nat On

You should change it to weak. assign is default for primitive types and should be used by primitive types. id is an object, so it should be either weak or strong - in this case weak, because you should not increase the reference counter.

You can read more about strong/weak/assign here, great explanation as far as I've noticed: SOF question about ARC.

Glad to see it's an important case for you as many people even not so new in Obj-C just 'skip' the problem and run into memory issues later.

-- edit --

Maybe you have any block inside and you're keeping a strong reference to self inside? Any dispatch or anything? Maybe you have property on another controller to this one and that's why it's still living?

0
Guillaume Algis On

From the Transitioning to ARC Release Notes:

assign is nearly the same thing as weak in the sense that it will not increment the retain count of the object, so it cannot be the source of your retain cycle.

The difference with weak is that when the pointed object is deallocated, a weak pointer will nil itself, but an assign (or __unsafe_unretained) pointer will still point to the free'd memory, resulting in a crash next time you try to dereference it.

tl;dr: you can keep assign, it is not the source of your memory issue, but using weak is safer and will produce less crashes (because messaging nil is a no-op).