Property not retained (ARC)

I have a modal view controller that is presented in the form sheet style. It has a protocol of delegates. I implement this protocol and appoint a delegate before the presentation, but it is lost, although the property is strong. Any possible reasons are welcome. Thanks!

Here is a property declaration as strong.

@protocol SDStoreViewDelegate <NSObject> // Methods @end @interface SDStoreViewController : UIViewController @property (strong, nonatomic) id <SDStoreViewDelegate> delegate; @end 

An object is created here and a set of delegates is set.

 SDStoreViewController *store = [[SDStoreViewController alloc] init]; [store setDelegate:self]; NSLog(@"1 %@",store.delegate); // Returns Object as expected [self presentViewController:store animated:YES completion:^{ NSLog(@"3 %@",store.delegate); // Returns Object as expected }]; NSLog(@"4 %@",store.delegate); // Returns Object as expected 

This is viewDidLoad from SDStoreViewController. He already lost a delegate

 - (void)viewDidLoad { [super viewDidLoad]; NSLog(@"3 %@",_delegate); // Returns NULL } 

This rejection is only because where the delegate will be called, it was not NULL.

 - (void)dismiss:(id)sender { NSLog(@"5 %@",_delegate); // Returns NULL [self.delegate aMethod]; } 

Update

I used weak and strong links. I also used self.delegate and _delegate to access the property. And as a point, the aMethod does not go through this, which prompted this detective work to find where it gets lost.

+4
source share
2 answers

first, the delegate property should always be weak or unsafe_unretained , otherwise ARC cannot unload classes with strong pointers to each other.

 @property (weak, nonatomic) id <SDStoreViewDelegate> delegate; 

or

 @property (unsafe_unretained, nonatomic) id <SDStoreViewDelegate> delegate; 

why didn't you try to get to the delegate property via getter? eg:

 NSLog(@"4 %@",self.delegate); 

instead

 NSLog(@"4 %@",_delegate); 

and bonus question: has your method been called back on this line?

 [self.delegate aMethod]; 

if the answer is yes, you did not lose the delegate , if the answer is no, where do you set the delegate to somewhere else?

+2
source

add the set and get method to the implementation file. next to the synthesis function.

 @synthesize delegate = _delegate; - (id)delegate{ return _delegate; // Add a breakpoint here } - (void) setDelegate:(id) delegate { if (_delegate != delegate){ _delegate = delegate; // Add a breakpoint here } } 

Also set a breakpoint in the initWithCoder: and see if it gets there correctly.

0
source

All Articles