Validating a valid delegation object before sending it a message

I try to implement a delegation pattern in Objective-C, however I sometimes experience a Bad Access exception when calling a delegate. This seems to be caused by the release of the delegate. Apple does not recommend saving delegates.

How can I check my delegate, if it is still valid, before trying to send him a message?

+3
source share
4 answers

If there is a chance that the delegate will be released by the installer, then something is wrong with your design. You should install delegates only on objects whose lifetime is shorter than the delegate itself. For example, setting a delegate to subview / controller is fine, because subview / controller has a shorter lifetime than the caller.

AFAIK, there is no reliable way to determine if an object has already been released.

+8
source

What Apple means to not hold delegates is that objects should not keep their delegates because they do not own them. These are only objects that process messages.

, . , , . , GC, , , GC, , iVar.

- , .

+3

Photoviewer http ; , ( HTTP- ) HTTP, BAD_ACCESS . , .delegate dealloc

+1

, Nico.

LazyTablesCode, , Apple UITableView. , .

In my code, I had a problem that sometimes the image upload ends when the form that needs to be called through the delegate was issued. I was forced to add this piece of code to the viewController code (dealloc method):

if (self.nsDictionaryWithObjectsDownloading != nil) {
    for (id theKey in self.nsDictionaryWithObjectsDownloading) {
        Myobj *downloader = [self.nsDictionaryWithObjectsDownloading objectForKey:theKey];
        downloader.delegate = nil;
    }
}

These lines seem to solve the problem. In any case, it would be very appreciated if this is a good solution or not, or even memory problems when running downloader.delegate = nil;

Thanks and hi

+1
source

Source: https://habr.com/ru/post/1718266/


All Articles