Consider the following snippet illustrating the problem of object destruction during method execution.
-(void)handleNotification:(id)notification{
//owner has reference so this is fine
self.foo += 1;
//call back to the owner/delegate, owner may set reference to nil
[self.delegate didFinish];
//if object has been dealloc'ed, it crashes
self.bar += 1; // CRASH
}
Actually, I cannot even reproduce the crash, because it only happens rarely, but I know it exists from Crashlytics reports.
I am trying to fix it by declaring a strong reference to self
:
-(void)handleNotification:(id)notification{
self.foo += 1;
MyObj *strongSelf = self;
[self.delegate didFinish];
strongSelf.bar += 1;
}
However I am not sure if it correct (as I said, I cannot reproduce it and check that crash has gone).
If this fix correct? Will this change guarantee that self
will not be destructed until end of the method?